Problem 394

Posted by Ruizhi Ma on October 22, 2020

Solution URL

https://leetcode.com/submissions/detail/412071922/

代码

class Solution {
    public String decodeString(String s) {
        //ans: https://leetcode-cn.com/problems/decode-string/solution/decode-string-fu-zhu-zhan-fa-di-gui-fa-by-jyd/
        //Time: O(N) Space: O(N)
        StringBuilder res = new StringBuilder();
        int multi = 0;
        LinkedList<Integer> stack_multi = new LinkedList<>();
        LinkedList<String> stack_res = new LinkedList<>();
        //遍历s中所有字符(包括数字,字母,左括号,右括号)
        for(Character c: s.toCharArray()){
            //如果是左括号 [
            if(c.equals('[')){
                //将数字和字符分别入栈,并且还原multi和res
                stack_multi.add(multi);
                stack_res.add(res.toString());
                multi = 0;
                res = new StringBuilder();
            }
            //如果是右括号 ]
            else if(c.equals(']')){
                StringBuilder temp = new StringBuilder();
                int cur_multi = stack_multi.removeLast();//弹出一次数字
                //根据弹出的数字n将之前的res,复制n次
                for(int i = 0; i < cur_multi; i++) temp.append(res);
                //将存字母的stack中元素弹出,和复制完的字符组合起来
                res = new StringBuilder(stack_res.removeLast() + temp);
            }
            //如果是数字,则赋值给multi(当然要处理一下比如12这样的数字)
            else if(c >= '0' && c <= '9') multi = multi * 10 + Integer.parseInt(c + "");
            //如果是字母
            else res.append(c);
        }

        return res.toString();
    }
}