【路飞】栈数据结构

141 阅读1分钟

「这是我参与11月更文挑战的第11天,活动详情查看:2021最后一次更文挑战

特点

  • 是一种线性的数据结构
  • 只能在一端(栈顶)进行插入和删除
  • 先进后出

应用

  • 撤销操作
  • 系统调用栈
  • 括号匹配

基本实现

class Stack {
  constructor() {
    this.data = [];
  }

  push(item) {
    this.data.push(item);
  }

  pop() {
    return this.data.pop();
  }

  peek() {
    return this.data[this.data.length - 1];
  }

  isEmpty() {
    return this.data.length === 0;
  }

  clear() {
    this.data = [];
  }

  size() {
    return this.data.length;
  }

  print() {
    console.log(this.data.toString());
  }
}

const stack = new Stack();
for (let i = 0; i < 6; i++) {
  stack.push(i);
  stack.print();
}
stack.pop();
stack.print();

题目:20. 有效的括号

image.png

解答

function isValid(s) {
  const arr = [];
  let isMatch = true;
  const mapper = {
    "(": ")",
    "{": "}",
    "[": "]",
  };
  for (let i = 0; i < s.length; i++) {
    const item = s[i];
    const isLeft = mapper[item];
    if (isLeft) {
      arr.push(item);
    } else {
      // 和栈顶元素相匹配
      const prev = arr.pop();
      if (item != mapper[prev]) {
        isMatch = false;
      }
    }
  }
  if (arr.length) {
    isMatch = false;
  }
  return isMatch;
};