Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string]
, where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a
or 2[4]
.
Examples:
s = "3[a]2[bc]", return "aaabcbc". s = "3[a2[c]]", return "accaccacc". s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
务必代入 s = "3[a2[c]]", return "accaccacc". 这个例子观察countStack,StringStack,res的变化过程
class Solution {
public String decodeString(String s) {
Stack<Integer> countStack = new Stack<>();
Stack<String> StringStack = new Stack<>();
int i = 0;
int count = 0;
String res = new String();
while(i<s.length()){
//数字情形单独处理,因为数字可能是32,132等多位数字
while(s.charAt(i)>='0'&&s.charAt(i)<='9'){
count = count*10 + s.charAt(i)-'0';
i++;
}
if(count!=0){
countStack.push(count);
count = 0;
}
if(s.charAt(i)=='['){//一旦遇到左括号,就把此时的res放入StringStack中,然后用res记录括号中的字符串
StringStack.push(res);
res = new String();
i++;
}
else if(s.charAt(i)==']'){//一旦遇到右括号,就将res恢复为此时应有的
String prev = StringStack.pop();
int n = countStack.pop();
for(int k = 0;k<n;k++){
prev += res;
}
res = prev;
i++;
}
else{//可能是左括号之内的小写字母或者是不加括号的小写字母
res += s.charAt(i);
i++;
}
}
return res;
}
}