码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode] Valid Parentheses @Python

时间:2014-10-01 01:40:20      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   sp   

https://oj.leetcode.com/problems/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.

Trick: 

Data structure: stack. LIFO (Last in first out)

class Solution:
    # @return a boolean
    def isValid(self, s):
        stack = []
        left, right = ([{, )]}
        for i in s:
            if i in left:
                stack.append(i); continue
            for j in range(3):
                if right[j] == i:
                    if not stack or stack[-1] != left[j]:
                        return False
                    else:
                        stack.pop()
                        continue
        return not stack

 

[leetcode] Valid Parentheses @Python

标签:style   blog   http   color   io   os   ar   for   sp   

原文地址:http://www.cnblogs.com/asrman/p/4002832.html

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