题目介绍
题解
代码如下:
class Solution {
public String decodeString(String s) {
StringBuilder res = new StringBuilder();
int multi = 0;
Stack<Integer> stack_multi = new Stack<>(); // 数字栈:保存嵌套层级的重复次数
Stack<String> stack_res = new Stack<>(); // 字符串栈:保存前面已经处理好的字符串
for(Character c : s.toCharArray()) {
if(c >= '0' && c <= '9'){
multi = multi * 10 + c - '0';
} else if(c == '[') {
stack_multi.push(multi); // 当前重复次数压栈
stack_res.push(res.toString());// 将前面处理好的字符串压栈保存一下
multi = 0; // 重置重复次数
res = new StringBuilder(); // 重置当前字符串
}
else if(c == ']') {
StringBuilder tmp = new StringBuilder();
int cur_multi = stack_multi.pop(); // 弹出重复次数
for(int i = 0; i < cur_multi; i++) { // 重复当前层字符串
tmp.append(res);
}
res = new StringBuilder(stack_res.pop() + tmp); // 拼接外层字符串
}else{
res.append(c);
}
}
return res.toString();
}
}