LeetCode_394(字符串解码)
双栈法
public String decodeString(String s) {
String res = "";
Stack<Integer> countStack = new Stack<>();
Stack<String> resStack = new Stack<>();
int idx = 0;
while (idx < s.length()){
char cur = s.charAt(idx);
//处理数字
if(Character.isDigit(cur)){
StringBuffer ret = new StringBuffer();
while (Character.isDigit(s.charAt(idx))){
ret.append(s.charAt(idx++));
}
countStack.push(Integer.parseInt(ret.toString()));
} else if (cur == '[') {
//处理[
resStack.push(res);
res = "";
idx++;
}else if(cur == ']'){
//处理']',处理相匹配的
StringBuffer temp = new StringBuffer(resStack.pop());
int repeatTimes = countStack.pop();
for(int i=0;i<repeatTimes;i++){
temp.append(res);
}
res = temp.toString();
idx++;
}else{
//处理普通字符
res+=s.charAt(idx++);
}
}
return res;
}
原文地址:https://blog.csdn.net/jklzbc/article/details/137291141
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!