20. Valid Parentheses
1. 题目
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
2. 思路
本题是验证给定的字符串,是不是有效的括号串。思路也很简单,可以用栈的方式实现。如果遇到了"[" ,"{" ,"("就入栈。如果遇到了"]" ,"}" ,")" 就出栈前一个字符,看前一个字符是否能匹配当前的字符。如果不行,则当前字符也入栈。最后程序结束的时候判断栈里面还有多少元素,如果是0则代表字符串是有效的括号串。
3. 实现
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
if len(s) == 0 : return True
for e in s :
if len(stack) == 0 :
stack.append(e)
continue
t = stack[-1]
if ( t == "(" and e == ")" ) or ( t == "{" and e == "}" ) or ( t == "[" and e == "]" ):
stack.pop(-1)
else:
stack.append(e)
if len(stack) == 0 :return True
return False