描述:
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例:
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
链接:字符串解码
思路分析:
使用栈、不停出栈、压栈
注意:需要特别考虑数字是多位的情况
代码实现:
class Solution {
public String decodeString(String s) {
Stack<String> stack = new Stack<>();
char[] c = s.toCharArray();
for (int idx = 0; idx < c.length; idx++) {
if (c[idx] != ']' && (c[idx] > '9' || c[idx] < '0')) {
stack.push(c[idx] + "");
} else if (c[idx] <= '9' && c[idx] >= '0') {
String numStr = "";
while (c[idx] <= '9' && c[idx] >= '0') {
numStr = numStr + c[idx];
idx++;
}
stack.push(numStr);
idx--;
} else {
String str = "";
while (!stack.peek().equals("[")) {
str = stack.pop() + str;
}
stack.pop();
int num = Integer.parseInt(stack.pop());
String newStr = "";
while (num > 0) {
newStr = str + newStr;
num--;
}
stack.push(newStr);
}
}
String ans = "";
while (!stack.isEmpty()) {
ans = stack.pop() + ans;
}
return ans;
}
}