LeetCode 20. 有效的括号(Valid Parentheses)

20. 有效的括号

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

有效字符串需满足:

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

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

示例 1:

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

示例 2:

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

示例 3:

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

示例 4:

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

示例 5:

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

 提示:

  • 1 <= s.length <= 104
  • s 仅由括号 '()[]{}' 组成

题解一(python):

 1 class Solution:
 2     def isValid(self, s: str) -> bool:
 3         dic = {')':'(',']':'[','}':'{'} # 字典
 4         stack = []
 5         for i in s:
 6             if stack and i in dic: # 若栈不为空且i为有效字符串
 7                 if stack[-1] == dic[i]: # 若栈顶元素能和dic[i]匹配,则出栈
 8                     stack.pop()
 9                 else: 
10                     return False # 否则就返回false
11             else: 
12                 stack.append(i) # 若i在栈中无,则压栈
13             
14         return not stack

 

上一篇:编译器实现之旅——第四章 实现词法分析器


下一篇:LeetCode 921 Minimum Add to Make Parentheses Valid (字符串 栈)