解决思路:
- 这道题我是真的没有想出来,我也知道用栈来做,但是却捋不清思路。所以这篇解法应该是评论区阅读量最高的那位老哥的解法。
- 主要是构造辅助栈,字符串栈跟数字栈(ps:我当时想的是一个,233333....)。然后是数字要明白不只是只有个位,还可能有白位千位之类的,注意特殊处理。然后是注意‘[’入栈,‘]’出栈,其实一切就很好做了。这里贴上老哥的思路。
class Solution {
public String decodeString(String s) {
Stack<Integer> multi_stack = new Stack<>();
Stack<String> res_stack = new Stack<>();
int multi = 0;
String res = "";
for(char c : s.toCharArray()){
if(c >= '0' && c <= '9'){
multi = multi * 10 + Integer.parseInt(c + "");
}else if(c == '['){
multi_stack.push(multi);
res_stack.push(res);
multi = 0;
res = "";
}else if(c == ']'){
int current_multi = multi_stack.pop();
String temp = "";
for(int i = 0; i < current_multi; i++){
temp += res;
}
res = res_stack.pop() + temp;
}else {
res += c;
}
}
return res;
}
}