1. 题目
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例 1:
输入:s = “3[a]2[bc]”
输出:“aaabcbc”
示例 2:
输入:s = “3[a2[c]]”
输出:“accaccacc”
示例 3:
输入:s = “2[abc]3[cd]ef”
输出:“abcabccdcdcdef”
示例 4:
输入:s = “abc3[cd]xyz”
输出:“abccdcdcdxyz”
Related Topics 栈 深度优先搜索
👍 636 👎 0
2. 题解
2.1 解法1: 辅助栈
算法流程:
构建辅助栈 stack, 遍历字符串 s 中每个字符 c;
-
当 c 为数字时,将数字字符转化为数字 multi,用于后续倍数计算;
-
当 c 为字母时,在 res 尾部添加 c;
-
当 c 为 [ 时,将当前 multi 和 res 入栈,并分别置空置 0:
(1) 记录此 [ 前的临时结果 res 至栈,用于发现对应 ] 后的拼接操作;
(2) 记录此 [ 前的倍数 multi 至栈,用于发现对应 ] 后,获取 multi × […] 字符串。
(3) 进入到新 [ 后,res 和 multi 重新记录。
-
当 c 为 ] 时,stack 出栈,拼接字符串 res = last_res + cur_multi * res,其中:
(1) last_res是上个 [ 到当前 [ 的字符串,例如 “3[a2[c]]” 中的 a;
(2) cur_multi是当前 [ 到 ] 内字符串的重复倍数,例如 “3[a2[c]]” 中的 2。
最后返回字符串 res
。
class Solution {
public String decodeString(String s) {
// 两个栈分别存储中间字符串及数字
LinkedList<StringBuffer> resStack = new LinkedList<>();
LinkedList<Integer> multiStack = new LinkedList<>();
int multi = 0;
StringBuffer res = new StringBuffer();
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
// 将数字字符转化为数字 multi,用于后续倍数计算;累计倍数
multi = multi * 10 + Integer.parseInt(c + "");
} else if (c == '[') {
// 此时将中间结果存入栈
// 记录此 [ 前的临时结果 res 至栈,用于发现对应 ] 后的拼接操作
multiStack.push(multi);
resStack.push(res);
multi = 0;
res = new StringBuffer();
} else if (Character.isAlphabetic(c)) {
res.append(c);
} else {
// 当 c 为 ] 时, stack 出栈,拼接字符串
int tempMulti = multiStack.pop();
StringBuffer tempRes = resStack.pop();
for (int i = 0; i < tempMulti; i++) {
tempRes.append(res);
}
res = tempRes;
}
}
return res.toString();
}
}
简略写法:
class Solution {
public String decodeString(String s) {
StringBuilder res = new StringBuilder();
int multi = 0;
LinkedList<Integer> stack_multi = new LinkedList<>();
LinkedList<String> stack_res = new LinkedList<>();
for (Character c : s.toCharArray()) {
if (c == '[') {
stack_multi.addLast(multi);
stack_res.addLast(res.toString());
multi = 0;
res = new StringBuilder();
} else if (c == ']') {
StringBuilder tmp = new StringBuilder();
int cur_multi = stack_multi.removeLast();
for (int i = 0; i < cur_multi; i++) tmp.append(res);
res = new StringBuilder(stack_res.removeLast() + tmp);
} else if (c >= '0' && c <= '9') multi = multi * 10 + Integer.parseInt(c + "");
else res.append(c);
}
return res.toString();
}
}