[Stack]Valid Parentheses
一、题目
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
二、解析
括号的匹配,用栈。这题非常简单,思路如下:
1、构建括号匹配规则,只有(:), [:], {:}才是合法的,因此构建一个dict存储这三种情况
2、构建一个栈(list, append=push, pop=pop),用来实现括号的进出
3、当栈顶元素与s当前匹配时,pop;不匹配就将s当前元素push
4、最后判断栈是否为空。为空说明全部匹配都弹出,返回True;否则返回False
三、代码
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ dic = {"(": ")", "[": "]", "{": "}"} stack = [] len_s = len(s) if len_s == 0: return True elif len_s == 1: return False else: for i in s: if len(stack) == 0: stack.append(i) else: if dic.get(stack[-1], 'None') == i: stack.pop() else: stack.append(i) if len(stack) == 0: return True else: return False
四、总结
1、使用变量len_s存储len(s),的确可以提升速度,从第三梯队上升到第二梯队