20. 有效的括号

题目来源:20. 有效的括号

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

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

方法一:栈

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
  if(s.length % 2 === 1){
    return false;
  }
  const pairs = new Map([
    [')','('],    
    [']','['],
    ['}','{']
  ])
  let stack = [];
  for(let ch of s){
    if(pairs.has(ch)){
      if(stack.length == 0 || stack[stack.length - 1] !== pairs.get(ch)){
        return false;
      }
      stack.pop();
    }else{
      stack.push(ch)
    }
  }
  return stack.length == 0;
};

示例 1:

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

示例 2:

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

示例 3:

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

示例 4:

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

示例 5:

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

 Python3

class Solution:
    def isValid(self, s: str) -> bool:
      if len(s) % 2 == 1:
        return False
      
      pairs = {
        ')':'(',
        ']':'[',
        '}':'{',
      }
      stack = list()

      for ch in s:
        if ch in pairs:
          if not stack or stack[-1] != pairs[ch]:
            return False
          stack.pop()
        else:
          stack.append(ch)
      return not stack

 

提示:

  • 1 <= s.length <= 104
  • s 仅由括号 '()[]{}' 组成
posted @ 2021-07-14 11:20  尖子  阅读(37)  评论(0编辑  收藏  举报