1. /**
    2. * @param {string} s
    3. * @return {string}
    4. */
    5. // 递归法
    6. var decodeString = function(s) {
    7. const o = {
    8. '[': 1,
    9. ']': -1,
    10. }
    11. const num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
    12. function copy(str, ind) {
    13. let newStr = ''
    14. let i = ind;
    15. while (i < str.length) {
    16. if (num.includes(str[i])) {
    17. const index = str.indexOf('[')
    18. const count = +(str.substr(i, index - i));
    19. let tempS = ''
    20. let t = 0;
    21. for (let j = index; j < str.length; j++) {
    22. if (o[str[j]] !== undefined) {
    23. t += o[str[j]]
    24. if (t === 0) {
    25. tempS = str.substr(index + 1, j - index - 1);
    26. i = j + 1;
    27. for (let k = 0; k < count; k++) {
    28. newStr += tempS;
    29. }
    30. newStr += str.substr(j + 1);
    31. if (newStr.indexOf('[') > -1) {
    32. newStr = copy(newStr, j + 1)
    33. }
    34. return newStr
    35. }
    36. }
    37. }
    38. } else {
    39. newStr += str[i]
    40. i++;
    41. }
    42. }
    43. return newStr
    44. }
    45. console.log(copy(s, 0));
    46. return copy(s, 0)
    47. };
    48. // 栈堆法
    49. var decodeString2 = (s) => {
    50. let stack = []
    51. for (const char of s) {
    52. if (char !== ']') { // ] 前的字符都入栈
    53. stack.push(char)
    54. // console.log(stack);
    55. continue
    56. }
    57. let cur = stack.pop() // 弹出一个来检测
    58. let str = '' // 组装字符串
    59. // 接下来肯定是遇到字母,直到遇到 [
    60. while (cur !== '[') {
    61. str = cur + str // cur字符加在左边
    62. cur = stack.pop() // 再拉出一个
    63. }
    64. // 此时cur为 [,接下来要遇到数字
    65. let num = ''
    66. cur = stack.pop() // 用下一个将 [ 覆盖
    67. while (!isNaN(cur)) {
    68. num = cur + num // 数字字符加在左边
    69. cur = stack.pop() // 再拉出一个
    70. }
    71. // 现在要么是字母,要么是 [
    72. console.log(cur);
    73. stack.push(cur)
    74. for (let j = 0; j < num; j++) {
    75. stack.push(str)
    76. }
    77. }
    78. console.log(stack.join(''), `stack.join('')`);
    79. return stack.join('')
    80. }
    81. decodeString2('x2[3[a]r4[ff]]hhh')