【路飞】字符串解码

84 阅读1分钟

题目:394. 字符串解码

image.png

解析

  1. 存储左括号前的字符串和数字,比如abc3[def], 当遇到第一个左括号的时候,压入栈中的是["abc", 3], 然后遍历括号里面的字符串def, 当遇到右括号的时候, 从栈里面弹出3"abc", 得到新的字符串为"abc"+"def".repeat(3), 也就是abcdefdefdef。对于括号里面嵌套的情况也是同样处理方式;
  2. 凡是遇到左括号就进行压栈处理,遇到右括号就弹出栈,栈中记录的元素很重要;
function decodeString(s) {
  let stack = [];
  let num = 0;
  let str = "";
  for (let i = 0; i < s.length; i++) {
    let c = s[i];
    if (c >= "0" && c <= "9") {
      num = 10 * num + parseInt(c);
    } else if (c === "[") {
      stack.push(str);
      stack.push(num);
      str = "";
      num = 0;
    } else if (c === "]") {
      const times = stack.pop();
      str = stack.pop() + str.repeat(times);
    } else {
      str += c;
    }
  }
  return str;
}