这道题目要实现的是字符串按照输入的格式进行解码,有点类似RLE算法,但是更复杂一点,因为这里有嵌套的解码,主要做法如下:
1、利用stack的先入后出性,设置countstack和resstack分别存储数字和字符;
2、当遇见‘【’时候,先把res放入resstack中,再reset为“”,来存储下次的字符
3、当遇见‘】’时候,先把resstack中pop,再加上下次要重复的字符(pop countstack 数字作为重复次数)。
代码如下:
public static String decodeString(String s) {
String res="";
Stack<Integer> countStack=new Stack<>();
Stack<String> resStack=new Stack<>();
int index=0;
while (index<s.length()) {
int count=0;
if (Character.isDigit(s.charAt(index))) {
while (Character.isDigit(s.charAt(index))) {
count=10*count+(s.charAt(index)-'0');
index++;
}
countStack.push(count);
}
else if (s.charAt(index)=='[') {
resStack.push(res);
res="";
index++;
}
else if (s.charAt(index)==']') {
StringBuffer sb=new StringBuffer(resStack.pop());
int num=countStack.pop();
for (int i = 0; i < num; i++) {
sb.append(res);
}
res=sb.toString();
index++;
}
else {
res +=s.charAt(index);
index++;
}
}
return res;
}