Decode String
用两个栈, 一个存储count, 一个存储遇到的string
新写的, 遇到了几个问题, 一个是每次遇到'['时忘记讲遇到的str压入栈中, 保证每次都是压入数字, 压入string
处理数字时, 尽量利用外层for-loop, 而不是新写一个while
public class Solution { public String decodeString(String s) { Stack<Integer> s1 = new Stack<Integer>(); Stack<String> s2 = new Stack<String>(); int count = 0;StringBuilder cur = new StringBuilder(); for(int i=0;i<s.length();){ if(Character.isDigit(s.charAt(i))){ StringBuilder num = new StringBuilder(); while(i<s.length()&&Character.isDigit(s.charAt(i))){ num.append(s.charAt(i)); i++; } count = Integer.valueOf(num.toString()); } if(s.charAt(i)=='['){ s1.push(count); s2.push(cur.toString()); count = 0; cur.setLength(0); } else if(s.charAt(i)==']'){ StringBuilder tmp = new StringBuilder(); int n = s1.pop(); for(int k=0;k<n;k++){ tmp.append(cur.toString()); } cur = new StringBuilder(s2.pop() + tmp.toString()); } else{ cur.append(s.charAt(i)); } i++; } return cur.toString(); } }
更好的版本
public class Solution {
public String decodeString(String input) {
Stack<Integer> counts = new Stack<Integer>();
Stack<String> strs = new Stack<String>();
String s = ""; int num = 0;
for(int i=0;i<input.length();i++){
char c = input.charAt(i);
if(Character.isDigit(c)){
num = num*10 + c-'0';
}
else if(c=='['){
strs.push(s);
counts.push(num);
s=""; num=0;
}
else if(c==']'){
int n = counts.pop();
StringBuilder sb = new StringBuilder();
for(int j=0;j<n;j++)
sb.append(s);
s = strs.pop() + sb.toString();
}
else if(Character.isLetter(c))
s+=c;
}
return s;
}
}