394. Decode string

Decode String - LeetCode Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won’t be input like 3a or 2[4].

Example 1: Input: s = “3[a]2[bc]” Output: “aaabcbc” Example 2: Input: s = “3[a2[c]]” Output: “accaccacc”


  • code
class Solution {
    public String decodeString(String s) {
        Stack<Integer> num_stack = new Stack<>();
        Stack<StringBuilder> str_stack = new Stack<>();
        int curnum = 0;
        StringBuilder curstr = new StringBuilder();
        for (char c: s.toCharArray()){
            if (Character.isDigit(c)){
                curnum = curnum * 10 + (c - '0');
            }
            else if (c == '['){
                num_stack.push(curnum);
                str_stack.push(curstr);
                curnum = 0;
                curstr = new StringBuilder();
            }
            else if (c == ']'){
                StringBuilder prestr = str_stack.pop();
                for (int num = num_stack.pop(); num > 0; num--){
                    prestr.append(curstr);
                }
                curstr = prestr;
            }
            else{
                curstr.append(c);
            }
        }
        return curstr.toString();
    }
}
  • code
class Solution(object):
    def decodeString(self, s):
        stack = []; curNum = 0; curString = ''
        for c in s:
            if c == '[':
                stack.append(curString)
                stack.append(curNum)
                curString = ''
                curNum = 0
            elif c == ']':
                num = stack.pop()
                prevString = stack.pop()
                curString = prevString + num*curString
            elif c.isdigit():     # curNum*10+int(c) is helpful in keep track of more than 1 digit number
                curNum = curNum*10 + int(c)
            else:
                curString += c
        return curString