题目描述:
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
测试用例保证输出的长度不会超过 105。
代码思路
1、正则 + 循环替换
思路
- 1:使用正则表达式,找到其中满足 数字[字母] 这样的子串,然后将其替换成指定格式(比方 3[a] => aaa)
- 2:替换完成后,保留替换的结果 rs
- 3:然后使用rs 循环步骤【1】直到找不到匹配子串
class Solution {
public String decodeString(String s) {
// 正则:匹配 k[xxx],其中 k 是数字,xxx 是字母
// (\d+) 匹配数字 k
// \[ 匹配字符 [
// ([a-zA-Z]+) 匹配字母
// \] 匹配 ]
String regex = "(\\d+)\\[([a-zA-Z]+)\\]";
while (true) {
// 找是否存在匹配片段
if (!s.matches(".*" + regex + ".*")) {
break; // 不存在退出循环
}
s = s.replaceAll(regex, m -> {
// m.group(1) 是 k
// m.group(2) 是 中括号内字符串
int count = Integer.parseInt(m.group(1));
String str = m.group(2);
// 拼接 count 次
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
sb.append(str);
}
return sb.toString();
});
}
return s;
}
}
“双栈(Two Stacks)解法”一个存数字,一个存字符串。
class Solution {
public String decodeString(String s) {
Stack<Integer> numStack = new Stack<>();
Stack<String> strStack = new Stack<>();
StringBuffer curstr = new StringBuffer();
int num = 0;
for(int i = 0;i<s.length();i++){
char ch = s.charAt(i);
if(Character.isAlphabetic(ch)){
curstr.append(ch);
} else if (Character.isDigit(ch)) {
num = num*10+ch-'0';
} else if (ch=='[') {
numStack.push(num);
strStack.push(curstr.toString());
curstr = new StringBuffer();
num=0;
}else{ //ch=']'
int curnum = numStack.pop();
StringBuffer temp = new StringBuffer(strStack.pop());
for(int j=0;j<curnum;j++){
temp.append(curstr);
}
curstr = temp;
}
}
return curstr.toString();
}
}
字符串解码算法解析
830

被折叠的 条评论
为什么被折叠?



