https://leetcode.cn/problems/decode-string/description/?envType=study-plan-v2&envId=top-100-liked
394. 字符串解码
已解答
中等
相关标签
相关企业
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
这个解法逻辑清晰一点,但是也不好想。拿一个输入跟着逻辑走一遍大概能理解
class Solution {
public String decodeString(String s) {
Stack<Integer> countStack = new Stack<Integer>();
Stack<String> stringStack = new Stack<String>();
int num = 0;
// res是不断解码中间过程也保存在这个变量
String res = "";
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if ('0' <= ch && ch <= '9') {
// 计算重复的次数,如果数字是大于9的情况。就不止一位数
num = num * 10 + (ch - '0');
} else if (ch == '[') {
countStack.push(num);
stringStack.push(res);
num = 0;
res = "";
} else if (ch == ']') {
int repeat = countStack.pop();
// 目前栈中的字符串。比如这个输入3[a]2[bc]。目前栈中的字符串为aaa,res为bc
String now = stringStack.pop();
for (int j = 0; j < repeat; j++) {
now = now + res;
}
res = now;
} else {
res = res + ch;
}
}
return res;
}
}