Thinking process
Several things need to remember
- the number of times to repeat of the following enclosed string
- what is the encoded string, what is its start? And what is its end?
- how to get the previous string and attach the repeated current string to it?
Discuss what things need to do if the current character is
- a number => remember this in a variable k
- a '[' => push k to stack and reset the k, push currStr to stack and reset the currStr
- a ']' => append the current k times to previous string
Mistakes
corner cases
- k = 100, but 100 are three separate digits
- using k = k * 10 + ch - '0'
https://discuss.leetcode.com/topic/57159/simple-java-solution-using-stack/4
public class Solution {
public String decodeString(String s) {
StringBuilder currStr = new StringBuilder();
Stack<Integer> repTimesStack = new Stack<>();
Stack<StringBuilder> strsStack = new Stack<>();
int k = 0;
for (char ch : s.toCharArray()) {
if (Character.isDigit(ch)) {
k = k * 10 + ch - '0';
} else if (ch == '[') {
strsStack.push(currStr);
currStr = new StringBuilder();
repTimesStack.push(k);
k = 0;
} else if (ch == ']') {
StringBuilder tmp = currStr;
currStr = strsStack.pop();
for (k = repTimesStack.pop(); k > 0; --k) {
currStr.append(tmp);
}
} else {
currStr.append(ch);
}
}
return currStr.toString();
}
}