对于这种带有括号的嵌套类的万能递归解法
https://leetcode-cn.com/problems/decode-string/

- f函数遇到右括号或者遇到整个字符串的结尾终止
- info 两个信息 1, 转化的结果是什么 2. 以哪里结尾

- 现在到5位置了,碰到左括号了,我直接调子函数f (6)




遇到右括号了,函数终止, 此时f(13)返回给上游函数它的值b以及结尾位置14, 上游函数知道结尾位置后,就可以继续往下算了,这也是为什么函数既需要返回值又需要返回结尾的原因



public String decodeString(String s) {return process(s.toCharArray(), 0).ans;}public class Info {public String ans;public int end;public Info(String ans, int end) {this.ans = ans;this.end = end;}}// s[i....] 何时停?遇到 ']' 或者遇到 s的终止位置,停止// 返回Infopublic Info process(char[] s, int i) {StringBuilder sb = new StringBuilder();int count = 0;while (i != s.length && s[i] != ']') {if (s[i] >= '0' && s[i] <= '9') {count = count * 10 + s[i++] - '0';} else if (s[i] == '[') {Info next = process(s, i + 1);for (int j = 0; j < count; j++) {sb.append(next.ans);}count = 0;i = next.end + 1;} else { //字母sb.append(s[i++]);}}return new Info(sb.toString(), i);}
同类题

