394、字符串解码

示例 1:

输入:s = "3[a]2[bc]"
输出:"aaabcbc"

示例 2:

输入:s = "3[a2[c]]"
输出:"accaccacc"

public static String decodeString(String s) {
Stack<Integer> numStack = new Stack<>(); //数字栈
Stack<String> strStack = new Stack<>(); //字符串栈
StringBuilder res = new StringBuilder();
int num = 0; //重复次数
//遍历每个字符
for (char ch : s.toCharArray()) {
if (ch >= '0' && ch <= '9') {
//把数字字符转成整型,因为可能不止是个位,而是十位百位,所以需要乘10
num = num * 10 + (ch - '0');
continue;
}
if (ch == '[') {
//把数字num压入数字栈中
numStack.push(num);
num = 0;
//把拼接的字符串也压入字符串栈中
strStack.push(res.toString());
res = new StringBuilder();
continue;
}
if (ch == ']') {
StringBuilder temp = new StringBuilder();
//取出数字栈的数字,进行循环复制
int count = numStack.pop();
//拼接
for (int i = 0; i < count; i++) {
temp.append(res);
}
res = new StringBuilder(strStack.pop() + temp);
continue;
}
//括号[]里的字符
res.append(ch);
}
return res.toString();
}
posted @ 2024-02-05 00:55  MarkLeeBYR  阅读(3)  评论(0编辑  收藏  举报