用两个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;
}
}
TBD