码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_num20_Valid Parentheses

时间:2015-03-04 19:14:54      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:   leetcode   

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 Stack:#定义栈 后进先出
    data=[]
    def push(self,item):
        self.data.append(item)
    def pop(self):
        if self.data == []:
            return False
        else:
            return self.data.pop()
    def length(self):
        return len(self.data)
    def clear(self):
        self.data=[]
        
class Solution:
    # @return a boolean
    def isValid(self, s):
        p={'(':')','[':']','{':'}'}
        stack=Stack()
        stack.clear()
        for c in s:
            if c in p.keys():
                stack.push(c)
            elif c in p.values():
                k=stack.pop()
                if k==False or p[k]!=c:
                    return False
            else:
                return False
        if stack.length() == 0:
            return True
        else:
            return False


leetcode_num20_Valid Parentheses

标签:   leetcode   

原文地址:http://blog.csdn.net/eliza1130/article/details/44062421

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!