存一道简单的算法题

30 阅读1分钟

image.png

因为很少刷乐扣,遇到这道题就卡住了,想了半天没思路,看了下提示用栈实现,大脑才运转起来

以下是我的执行函数:

      const map = new Map();
      map.set(")", "(");
      map.set("}", "{");
      map.set("]", "[");
      function foo(str = "") {
        if (str === "") {
          return true;
        } else {
          const arr = [];
          str.split("").forEach((item) => {
            arr.push(item);
            // 只有一项的时候不对比
            // 左括号最后一次在栈出现位置的前一个位置与最新push进去的括号匹配
            if (
              arr.length > 1 &&
              arr[arr.lastIndexOf(item) - 1] === map.get(item)
            ) {
              // 移除相邻两个
              arr.pop();
              arr.pop();
            }
          });
          return arr.length === 0;
        }
      }
      console.log(foo("(){}[]"));  // true
      console.log(foo("({})[]"));  // true
      console.log(foo("({[]})"));  // true
      console.log(foo("[]({})"));  // true
      console.log(foo("({({}[])}[])"));  // true
      console.log(foo("}({][)"));  // false