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不含有[].
1 class Solution { 2 public String decodeString(String s) { 3 return helper(s, 0, s.length() - 1); 4 } 5 6 private String helper(String s, int start, int end) { 7 StringBuilder sb = new StringBuilder(); 8 for (int i = start; i <= end; i++) { 9 if (isDigit(s.charAt(i))) { 10 int num = 0; //取出数字 11 while(i <= end && s.charAt(i) != '[') { 12 num = num * 10 + s.charAt(i) - '0'; 13 i++; 14 } 15 int count = 0, j = i + 1; //取出[]的起始点,起点是j - 1, 终点是 i。 16 while(i < end) { 17 if (s.charAt(i) == '[') { 18 count++; 19 } else if (s.charAt(i) == ']') { 20 count--; 21 } 22 if (count == 0) { 23 break; 24 } 25 i++; 26 } 27 String str = helper(s, j, i - 1); 28 sb.append(generateString(str, num)); 29 } else { 30 sb.append(s.charAt(i)); 31 } 32 } 33 return sb.toString(); 34 } 35 private String generateString(String s, int count) { 36 StringBuilder str = new StringBuilder(); 37 for (int i = 1; i <= count; i++) { 38 str.append(s); 39 } 40 return str.toString(); 41 } 42 43 private boolean isDigit(char ch) { 44 return ch >= '0' && ch <= '9'; 45 } 46 }
本文介绍了一种用于解码特定格式字符串的算法,该算法能够处理包含重复子串的字符串,通过递归调用辅助函数来解析方括号内的内容,最终返回完全解码后的字符串。
1185

被折叠的 条评论
为什么被折叠?



