其他分享
首页 > 其他分享> > LeetCode 20. 有效的括号(Valid Parentheses)

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

 提示:

题解一(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

 

标签:Parentheses,20,示例,brackets,dic,括号,Valid,false,stack
来源: https://www.cnblogs.com/Dennis-Chen/p/leetcode_ValidParentheses.html