Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.python
An input string is valid if:app
Note that an empty string is also considered valid.ide
Example 1:code
Input: "()" Output: true
Example 2:字符串
Input: "()[]{}" Output: true
Example 3:input
Input: "(]" Output: false
Example 4:string
Input: "([)]" Output: false
Example 5:io
Input: "{[]}" Output: true
本题是验证给定的字符串,是否是有效的括号串。思路也很简单,能够用栈的方式实现。若是遇到了"[" ,"{" ,"("就入栈。若是遇到了"]" ,"}" ,")" 就出栈前一个字符,看前一个字符是否能匹配当前的字符。若是不行,则当前字符也入栈。最后程序结束的时候判断栈里面还有多少元素,若是是0则表明字符串是有效的括号串。class
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