leetcode #20 Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

  • 题目大意
    判断一个包含括号的字符串是否匹配,包括3种括号('(','[','{')

维护一个栈,遇到左括号就压入栈,遇到右括号就把栈顶的弹出看是否匹配。
注意最后要检查栈是否为空。

/**
 * @param {string} s
 * @return {boolean}
 */
const isValid = function (s) {
  const stack = [];
  const leftSet = new Set(['(', '[', '{']);
  const rightSet = new Set([')', ']', '}']);
  const pair = {
    ')': '(',
    ']': '[',
    '}': '{',
  };
  for (let i = 0; i < s.length; i++) {
    const char = s[i];
    if (leftSet.has(char)) {
      stack.push(char);
    }
    if (rightSet.has(char)) {
      if (stack.pop() !== pair[char]) {
        return false;
      }
    }
  }
  return stack.length === 0;
};

推荐阅读更多精彩内容