一.问题描述
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
二.解题思路
括号,有点类似做一个计算器,读入表达式输出结果,不过显然要比那个简单一点。
实现方法就是用栈(先进后出)来处理。
对于我们知道,单单出现一个左括号,我们没办法做任何操作,因为不知道后面会不会有该右括号,因此直接入栈。
出现一个右括号的时候,我们开始匹配,将上一个元素出栈(如果栈非空),判断它是不是该右括号匹配的左括号,不是的话返回False。
可能有人会说为啥直接判断上一个元素和现在括号匹配就行了,之前的元素也有可能啊。比如说'(())'这种情况。
仔细思考,我们现在是碰到右括号就处理,因此如果是一个正确的括号匹配的字符串,至少在我当前要匹配的左右括号之间不存在右括号,因为右括号已经被处理了。那么,如果是一个正确的括号匹配的字符串,在我当前待处理的左右括号之间应该是没有任何括号的(匹配的括号都已被弹出),因此如果上一个元素不是和现在的右括号匹配的左括号,那么说明不是一个正确的括号匹配字符串。
注意:
1.如果一个字符串全部都是左括号,可能就不会进入到右括号处理程序(没办法判断正确与否),此时只需要判断栈是否空就好,如果是一个正确括号匹配字符串,处理完栈肯定为空。
2.空字符串是True
时间复杂度:O(N),空间复杂度O(N)
更多leetcode算法题解法: 专栏 leetcode算法从零到结束 或者 leetcode 解题目录 Python3 一步一步持续更新~
三.源码
class Solution:
def isValid(self, s: str) -> bool:
prs_match={'}':'{',']':'[',')':'('}
stack,res=[],True
for ch in s:
if ch not in prs_match:stack.append(ch)
else:
if not stack or stack.pop()!=prs_match[ch]:
res=False
break
return res and not stack