394. 字符串解码
作者:
名字是乱打的 | 来源:发表于
2021-12-20 22:55 被阅读0次
一 题目:
二 思路:
- 利用辅助栈记录循环次数以及拼好的字符串
- 利用count=count*10+(c-'0');解决数字可能是多位的问题
三代码:
class Solution {
public String decodeString(String s) {
//括号前的数量,用于做倍数计算
LinkedList<Integer> countStack=new LinkedList<>();
//字符串栈
LinkedList<String> strStack=new LinkedList<>();
StringBuilder sb=new StringBuilder();
int count=0;
//eg:输入:s = "3[a]2[bc]"
for (char c : s.toCharArray()) {
if (c>='0'&&c<='9'){
count=count*10+(c-'0');
}else if (c>='a'&&c<='z'){
sb.append(c);
}else if (c=='['){
countStack.push(count);
strStack.push(sb.toString());
sb=new StringBuilder();
count=0;
}else {
//c==]
StringBuilder currSb=new StringBuilder();
currSb.append(strStack.pop());
Integer currCount = countStack.pop();
for (int i = 0; i < currCount; i++) {
currSb.append(sb);
}
sb=currSb;
}
}
return sb.toString();
}
}
本文标题:394. 字符串解码
本文链接:https://www.haomeiwen.com/subject/baltqrtx.html
网友评论