Decode String

时间:2021-04-26 08:38:58

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".

思路:这题的思路和basic calculator一样,我们构建一个helper fuction,用来处理没有[]的情况,basic calculator是处理有()的情况。也就是说,如果遇到有[],我们需要把[]的起始点和终点找到,
然后call那个helper function, 直到传入到helper function的string不含有[].

 class Solution {
public String decodeString(String s) {
return helper(s, , s.length() - );
} private String helper(String s, int start, int end) {
StringBuilder sb = new StringBuilder();
for (int i = start; i <= end; i++) {
if (isDigit(s.charAt(i))) {
int num = ; //取出数字
while(i <= end && s.charAt(i) != '[') {
num = num * + s.charAt(i) - '';
i++;
}
int count = , j = i + ; //取出[]的起始点,起点是j - 1, 终点是 i。
while(i < end) {
if (s.charAt(i) == '[') {
count++;
} else if (s.charAt(i) == ']') {
count--;
}
if (count == ) {
break;
}
i++;
}
String str = helper(s, j, i - );
sb.append(generateString(str, num));
} else {
sb.append(s.charAt(i));
}
}
return sb.toString();
}
private String generateString(String s, int count) {
StringBuilder str = new StringBuilder();
for (int i = ; i <= count; i++) {
str.append(s);
}
return str.toString();
} private boolean isDigit(char ch) {
return ch >= '' && ch <= '';
}
}