Leetcode Day5 20. Valid Parentheses Python 栈的实现

来源:互联网 发布:淘宝拒签后怎么处理 编辑:程序博客网 时间:2024/05/16 08:26

今天leetcode遇到一道括号匹配的问题,首先想到用栈这种数据结构。

http://www.jianshu.com/p/1387fe93891c 查到这篇栈的实现,不错

进而想起前几天同学问我的list里的remove和pop有什么区别,今天查了一下这个答案不错 

http://novell.me/master-diary/2014-06-05/difference-between-del-remove-and-pop-on.html

只是有一点需要更正,实践可知:在python3中,list.pop() == something 时并不会输出弹出的值


20. 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.


class Solution:    def isValid(self,s):        if ("]" not in s and "}" not in s and ")" not in s): #防止类似"{(["这种只有左括号的输入            return False        visualStack=[]#创建虚拟栈        for char in s:            if char not in ["[","{","(","}",")","]" ]:#防止错误输入                   return  False            if char in ["[" , "{" , "("]:#遇到左括号就入栈                   visualStack.append(char)            if len(visualStack)==0:#防止只有右括号的输入,比如")]}"就会在这里返回False                  return  False            else:#括号不匹配                 if char == "}" and  visualStack.pop()!="{":                      return False                 if char == ")" and   visualStack.pop()!="(":                      return False                 if (char == "]") and visualStack.pop() != "[":                      return False        return visualStack==[]#如果栈没弹空就代表左括号比右括号多sol=Solution()print ("result is",sol.isValid("([]"))

这个方法虽然笨但是我竟然写了好久T^T,跑了45ms

看到一个更简洁的做法:

class Solution:    # @return a boolean    def isValid(self, s):        stack = []        dict = {"]":"[", "}":"{", ")":"("}        for char in s:            if char in dict.values():                stack.append(char)            elif char in dict.keys():                if stack == [] or dict[char] != stack.pop():                    return False            else:                return False        return stack == []



原创粉丝点击