Skip to content

20. 有效的括号

给定一个只包括 '('')''{''}''['']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。
  3. 每个右括号都有一个对应的相同类型的左括号。

示例 1:

输入:s = "()"
输出:true
输入:s = "()"
输出:true

示例 2:

输入:s = "()[]{}"
输出:true
输入:s = "()[]{}"
输出:true

示例 3:

输入:s = "(]"
输出:false
输入:s = "(]"
输出:false

提示:

  • 1 <= s.length <= 104
  • s 仅由括号 '()[]{}' 组成
js
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function (s) {
  if (s.length % 2 !== 0) {
    return false
  }

  const pairs = new Map([
    [')', '('],
    [']', '['],
    ['}', '{'],
  ])
  const stack = []

  for (const ch of s) {
    if (pairs.has(ch)) {
      if (!stack.length || pairs.get(ch) !== stack[stack.length - 1]) {
        return false
      }
      stack.pop()
    } else {
      stack.push(ch)
    }
  }

  return !stack.length
};
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function (s) {
  if (s.length % 2 !== 0) {
    return false
  }

  const pairs = new Map([
    [')', '('],
    [']', '['],
    ['}', '{'],
  ])
  const stack = []

  for (const ch of s) {
    if (pairs.has(ch)) {
      if (!stack.length || pairs.get(ch) !== stack[stack.length - 1]) {
        return false
      }
      stack.pop()
    } else {
      stack.push(ch)
    }
  }

  return !stack.length
};

Released under the MIT License.