Skip to content

Latest commit

 

History

History
33 lines (26 loc) · 651 Bytes

20.有效的括号.md

File metadata and controls

33 lines (26 loc) · 651 Bytes

思路

利用栈,如果右括号不匹配则返回false,匹配则持续出栈,如果栈内还有元素则说明有剩余,没有匹配完全

代码

var isValid = function(s) {
  const stack = [];
  const key = ['(', '{', '[']
  const value = [')', '}', ']'];
  for(let i = 0; i < s.length; i++) {
    let cur = s[i];
    if (key.includes(cur)) {
      stack.push(cur);
    } else {
      let index = value.indexOf(cur);
      let last = stack.pop();
      if (key[index] != last) {
        return false;
      }
    }
  }
  return !stack.length
};

复杂度分析

时间复杂度 $O(N)$

空间复杂度 $O(N)$