leetcode 394. 字符串解码

leetcode 394. 字符串解码
主要思路是用两个栈,一个数字栈,一个字符串栈,把数字放入数字栈中,把左括号和字母放到字符串栈中(左括号主要为了处理括号嵌套情况)

class Solution {
    public static String decodeString(String s) {
        Deque<Integer> numStack=new LinkedList<>();
        Deque<String> strStack=new LinkedList<>();
        StringBuffer numBuffer=new StringBuffer();//数字栈
        StringBuffer strBuffer=new StringBuffer();//字符串栈
        for(int i=0;i<s.length();i++){
            if(s.charAt(i)>=48&&s.charAt(i)<=57){
                numBuffer.append(s.charAt(i));
                if(strBuffer.length()>0){
                    strStack.offerFirst(strBuffer.toString());
                    strBuffer.setLength(0);
                }
            }else if(s.charAt(i)>=97&&s.charAt(i)<=122){
                strBuffer.append(s.charAt(i));
            }else if(s.charAt(i)=='['){
                if(numBuffer.length()>0){
                    int num=Integer.valueOf(numBuffer.toString());
                    numStack.offerFirst(num);
                    numBuffer.setLength(0);
                }
                if(strBuffer.length()>0){
                    strStack.offerFirst(strBuffer.toString());
                    strBuffer.setLength(0);
                }
                strStack.offerFirst("[");
            }else if(s.charAt(i)==']'){
                if(strBuffer.length()>0){
                    strStack.offerFirst(strBuffer.toString());
                    strBuffer.setLength(0);
                }
                int num2=numStack.pollFirst();
                StringBuffer t=new StringBuffer();//拼接栈中[括号以前的
                StringBuffer t2=new StringBuffer();//存放翻倍的字符串

                while(!"[".equals(strStack.peekFirst())){
                    String t3=strStack.pollFirst();
                    t.insert(0,t3);
                }
                while(num2>0){
                    t2.append(t.toString());
                    num2--;
                }
                strStack.pollFirst();//再弹出[
                strStack.offerFirst(t2.toString());
            }
        }
        StringBuffer res=new StringBuffer();
        while (!strStack.isEmpty()){
            res.append(strStack.pollLast());
        }
        if(strBuffer.length()>0){
            res.append(strBuffer.toString());
        }
        return res.toString();

    }
}

你可能感兴趣的:(leetcode,leetcode,算法,职场和发展)