LeetCode-394-字符串解码

思路
使用2个栈分别存储“[“前的字符串和数字
- ch[i]=数字:num=num*10+数字
- ch[i]=字符:res+=字符;
- ch[i]=’[’:num和res入栈,置0置空
- ch[i]=’]’:出栈,计算字符串,次数=nums.pop(),str=strs.pop(),拼接str和res,res更新为str
代码
class Solution {
public String decodeString(String s) {
Stack<Integer> nums=new Stack<>();//存放"["前的数字
Stack<StringBuilder> strs=new Stack<>();//存放"["前的字符串
char[] ch=s.toCharArray();
StringBuilder res=new StringBuilder("");//保存当前遍历到的字符串
int num=0;
for(int i=0;i<ch.length;i++){
if(ch[i]>='0'&&ch[i]<='9')num=num*10+ch[i]-'0';//可能是多位数字因此必须num*10
else if((ch[i]>='a'&&ch[i]<='z')||(ch[i]>='A'&&ch[i]<='Z')){
res.append(ch[i]);//字符串拼接
}
else if(ch[i]=='['){
//遇到"[",全部入栈,临时变量置0置空
nums.push(num);
num=0;
strs.push(res);
res=new StringBuilder("");
}
else{
//遇到"]",栈顶出栈进行计算
int times=nums.pop();//表示当前res的次数
StringBuilder str=strs.pop();//表示[]前的字符串,用于拼接[]中的字符串
for(int j=0;j<times;j++){
str.append(res);//拼接
}
res=new StringBuilder(str);//res更新为拼接后的字符串
}
}
return res.toString();
}
}
本文详细介绍了如何解决LeetCode第394题——字符串解码问题。通过使用两个栈分别存储数字和子串,逐一解析字符串,遇到'['和']'时进行相应操作,最终得到解码后的字符串。核心思路在于栈的应用和数字计算。

被折叠的 条评论
为什么被折叠?



