对于这种带有括号的嵌套类的万能递归解法

https://leetcode-cn.com/problems/decode-string/

image.png

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

image.png

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

image.png

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

  1. public String decodeString(String s) {
  2. return process(s.toCharArray(), 0).ans;
  3. }
  4. public class Info {
  5. public String ans;
  6. public int end;
  7. public Info(String ans, int end) {
  8. this.ans = ans;
  9. this.end = end;
  10. }
  11. }
  12. // s[i....] 何时停?遇到 ']' 或者遇到 s的终止位置,停止
  13. // 返回Info
  14. public Info process(char[] s, int i) {
  15. StringBuilder sb = new StringBuilder();
  16. int count = 0;
  17. while (i != s.length && s[i] != ']') {
  18. if (s[i] >= '0' && s[i] <= '9') {
  19. count = count * 10 + s[i++] - '0';
  20. } else if (s[i] == '[') {
  21. Info next = process(s, i + 1);
  22. for (int j = 0; j < count; j++) {
  23. sb.append(next.ans);
  24. }
  25. count = 0;
  26. i = next.end + 1;
  27. } else { //字母
  28. sb.append(s[i++]);
  29. }
  30. }
  31. return new Info(sb.toString(), i);
  32. }

同类题

image.png