二刷394. Decode String

Medium
Given an encoded string, return it's 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].

Examples:

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

刷Yelp OA题的时候看到的,以前做过,但是不看以前的记录还是不会做。根本想不到用两个Stack。 具体细节也是看了答案才想起来,但基本上看一眼就想起来当时的思路了,有些地方确实比较巧比较细,不太好想。比如记录下当前已经积累的String到sb存到sbStack里面,比如每次都new一个sb来记录当下String,比如为了解决可能的两位数采取repeat *= 10再 repeat += c - ‘0’等等。

class Solution {
    public String decodeString(String s) {
        Stack sbStack = new Stack<>();
        Stack intStack = new Stack<>();
        StringBuilder sb = new StringBuilder();
        int repeat = 0;
        for (char c : s.toCharArray()){
            if (c == '['){
                intStack.push(repeat);
                repeat = 0;
                sbStack.push(sb);
                sb = new StringBuilder();
            } else if (c == ']'){
                repeat = intStack.pop(); 
                String temp = sb.toString();
                sb = sbStack.pop();
                while (repeat > 0){
                    sb.append(temp);
                    repeat--;
                }
            } else if (c >= '0' && c <= '9'){
                repeat *= 10;
                repeat += c - '0';
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

你可能感兴趣的:(二刷394. Decode String)