November 22, 2019

394. Decode String

394. Decode String

Sol 1. Stack

用两个stack.
stack 1: track numbers;
stack 2: stack strings

  • 遇到数字:形成完整的数字
  • 遇到字母:形成完整的编码字符串
  • 遇到[:把之前记录的编码字符串压栈
  • 遇到]:完成解码的功能,即重复编码字符串n次。

题解参考了这个帖子.

class Solution {
    public String decodeString(String s) {
        String res = "";
        Deque<Integer> countStack = new ArrayDeque<>();
        Deque<String> resStack = new ArrayDeque<>();
        int index = 0;
        while (index < s.length()) {
            if (Character.isDigit(s.charAt(index))) {
                int count = 0;
                while (Character.isDigit(s.charAt(index))) {
                    count = 10 * count + (s.charAt(index) - '0');
                    index ++;
                }
                countStack.offerFirst(count);
            } else if (s.charAt(index) == '[') {
                resStack.offerFirst(res);
                res = "";
                index ++;
            } else if (s.charAt(index) == ']') {
                StringBuilder temp = new StringBuilder(resStack.pollFirst());
                int repeatedTimes = countStack.pollFirst();
                for (int i = 0; i < repeatedTimes; i++) {
                    temp.append(res);
                }
                res = temp.toString();
                index ++;
            } else {
                res += s.charAt(index++);
            }
        }
        return res;
    }
}

Sol 2. Recursive

TBD

comments powered by Disqus