20. Valid Parentheses

25 年 8 月 26 日 星期二
186 字
1 分钟

20. Valid Parentheses

Screenshot 2025-08-26 at 5.18.54 pm

注意三个cases

js
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function (s) {
  const st = []
  for (const c of s) {
    if (c === '(' || c === '[' || c === '{') {
      st.push(c)
    } else {
      // ) ] }
      // 如果栈为空一定不匹配
      if (st.length === 0) {
        return false
      }
      const t = st.pop()
      if (c === ')' && t !== '(') {
        return false
      } else if (c === ']' && t !== '[') {
        return false
      } else if (c === '}' && t !== '{') {
        return false
      }
    }
  }
  if (st.length) {
    return false
  }
  return true
}

长度不为双数直接返回False

python
        if n % 2 != 0:
            return False

stack为空直接返回False,如果栈为空一定不匹配

python
            else:
                if stack == []:
                    return False

判断最后stack为空

python
return True if stack == [] else False

文章标题:20. Valid Parentheses

文章作者:Sirui Chen

文章链接:https://blog.siruichen.me/posts/20_valid_parentheses[复制]

最后修改时间:


商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,您可以自由地在任何媒体以任何形式复制和分发作品,也可以修改和创作,但是分发衍生作品时必须采用相同的许可协议。
本文采用CC BY-NC-SA 4.0进行许可。