题目描述:

思路解析:
先搞清字符串的解码逻辑:解码总是让括号里的字符乘以括号前的次数再加上外层的字符串。所以可以用两个栈分别记录次数和外层的字符。
首先解析字符串 s,遇到数字时记录重复次数,遇到字符串时记录此时的字符串,遇到 [ 时进入新一层嵌套,遇到 ] 时将当前层的内容重复相应次数并与上一层合并。(此操作同样需要记录的字符串)
使用栈来处理嵌套结构:
- 一个栈用于存储重复次数(stack_num)。
- 一个栈用于存储字符串片段(stack_string)。
- 遍历字符串的每个字符:
- 如果是数字,累加计算重复次数 num。
- 如果是 [,将当前 num 和当前构建的字符串 res 压入栈,重置 num 和 res。
- 如果是 ],弹出栈顶的重复次数 a,将当前 res 重复 a 次,然后与栈顶的字符串合并。
- 如果是普通字符,直接追加到当前 res 中。
- 最终 res 即为解码后的字符串。
代码实现:
java
class Solution {
public String decodeString(String s) {
StringBuilder res=new StringBuilder();
int num=0;
LinkedList<Integer> stack_num=new LinkedList<>();
LinkedList<String> stack_string=new LinkedList<>();
for(Character c:s.toCharArray()){
if(c=='['){
stack_num.addLast(num);
stack_string.addLast(res.toString());
num=0;
res=new StringBuilder();
}else if(c==']'){
StringBuilder temp =new StringBuilder();
int a=stack_num.removeLast();
for(int i=0;i<a;i++){
temp.append(res);
}
res=new StringBuilder(stack_string.removeLast()+temp.toString());
}else if(c>='0'&&c<='9'){
num=num*10+Integer.parseInt(c+"");
}
else{
res.append(c);
}
}
return res.toString();
}
}
代码详解
- 初始化:
- res:当前正在构建的字符串片段(StringBuilder 高效追加)。
- num:当前解析的重复次数。
- stack_num 和 stack_string:分别存储嵌套层的重复次数和字符串前缀。
- 遍历字符:
- 遇到 [:压入当前 num 和 res,重置它们,开始新层。
- 遇到 ]:弹出重复次数 a,用 temp 构建重复的 res,然后与弹出栈的字符串合并(处理嵌套)。
- 遇到数字:累加到 num(多位数如 10 处理为 1*10 + 0)。
- 遇到字母:直接追加到 res。
- 示例 walkthrough(以 "3[a2[c]]" 为例):
- 开始:res="", num=0
- '3':num=3
- '[':压入 num=3, res="";重置 num=0, res=""
- 'a':res="a"
- '2':num=2
- '[':压入 num=2, res="a";重置 num=0, res=""
- 'c':res="c"
- ']':弹出 a=2, temp="cc";res="a" + "cc" = "acc"
- ']':弹出 a=3, temp="accaccacc";res="" + "accaccacc" = "accaccacc"
最终返回 "accaccacc"。