leetcode 394 解码

这种题算是常规题了,思路也比较固定:利用栈,扫一遍就可以了。直接上代码。

ublic static String decodeString(String s) {
        char[] sC = s.toCharArray();
        int len = s.length();
        int indx = 0;
        char nowC;
        StringBuffer digit = new StringBuffer();
        LinkedList<String> stackS= new LinkedList<>();
        while (indx<len){
            nowC = sC[indx];
            digit.setLength(0);
            while (nowC>='0'&&nowC<='9'){
                digit.append(nowC);
                nowC=sC[++indx];
            }
            if(digit.length()>0) stackS.addLast(digit.toString());
            if(nowC!=']'){
                stackS.addLast(String.valueOf(nowC));
                indx++;

            }else{
                indx++;
                String sub = new String();
                while (!stackS.peekLast().equals("[")){
                    sub = stackS.removeLast()+sub;
                }
                stackS.removeLast();
                //sub = sub.reverse();
                StringBuffer tmp = new StringBuffer(sub.toString());
                int time = Integer.parseInt(stackS.removeLast());

                for(int i=1;i<time;i++){
                    tmp.append(sub.toString());
                }
                stackS.addLast(tmp.toString());
            }

        }
        StringBuffer ans = new StringBuffer();
        for(String tmp : stackS){
            ans.append(tmp);
        }
        return ans.toString();
    }
View Code

这里要注意的是,java没有栈这种结构(好像有,但是不常用),我们用Linkedlist来模拟栈的特点。

原文地址:https://www.cnblogs.com/superxuezhazha/p/12983243.html