解题思路:
利用 栈 的先进后出原则来进行存储, 首先创建两个栈 一个栈用来存放 循环遍历的次数,另一个用来存储 本次循环遍历 拼接的值
Stack<String> stringStack=new Stack<>(); Stack<Integer> integerStack=new Stack<>();如果遇到了数字那么 就先用 stringbuff进行存储 然后遍历后续位数 如果后续依然是 数字则存储到 stringbuff中 直到 不是数字为止
StringBuffer stringBuffer=new StringBuffer(); while (Character.isDigit(s.charAt(idx))){ stringBuffer.append(s.charAt(idx++)); } integerStack.push(Integer.parseInt(stringBuffer.toString()));如果是"[" 证明上一次的存储字符已经结束,我们将变量res字符放入stringStack中并将 res清空
stringStack.push(res); res=""; idx++;如果是 "]" 证明我们本次的'[xxxxxx...xxx]" 已经结束,我们取出 stringStack的顶部栈中的字符 并取出 integerStack 中顶部的数字number为我们遍历次数来拼接字符串最后 res拼接完成本次 "[xxxxxx..]"中的字符串
StringBuffer stringBuffer=new StringBuffer(stringStack.pop()); int timeRepeat=integerStack.pop(); for (int i = 0; i < timeRepeat; i++) { stringBuffer.append(res); } res=stringBuffer.toString(); idx++;如果依然是字符 那么我们让res进行拼接
res+=s.charAt(idx++);
完整代码:
package 字符串解码;
import java.util.Stack;
public class DecodeString {
public static void main(String[] args) {
String s = decodeString("3[a2[c]]");
System.out.println("----------------------------结果是-----------------------");
System.out.println(s);
}
public static String decodeString(String s){
Stack<String> stringStack=new Stack<>();
Stack<Integer> integerStack=new Stack<>();
int idx=0;
String res="";
while (idx<s.length()){
char chart=s.charAt(idx);
if(Character.isDigit(chart)){
StringBuffer stringBuffer=new StringBuffer();
while (Character.isDigit(s.charAt(idx))){
stringBuffer.append(s.charAt(idx++));
}
integerStack.push(Integer.parseInt(stringBuffer.toString()));
}
else if(chart=='['){
System.out.println("---------res"+res);
stringStack.push(res);
res="";
idx++;
}
else if(chart==']'){
StringBuffer stringBuffer=new StringBuffer(stringStack.pop());
int timeRepeat=integerStack.pop();
for (int i = 0; i < timeRepeat; i++) {
stringBuffer.append(res);
}
res=stringBuffer.toString();
idx++;
}else{
res+=s.charAt(idx++);
}
}
return res;
}
}