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

Leetcode 栈 Valid Parentheses

时间:2014-09-07 16:03:05      阅读:168      评论:0      收藏:0      [点我收藏+]

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

Valid Parentheses

 Total Accepted: 17916 Total Submissions: 63131My Submissions

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.遇到左括号就压栈

2.遇到右括号就判断栈顶的括号和当前的括号是否是一对,如果栈为空或不匹配,说明整个字符串的括号不匹配,如果匹配,则将栈顶括号出栈

3.如果最终栈中的元素为0,则说明字符串匹配,否则不匹配

复杂度:时间O(n),空间O(n)

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

Leetcode 栈 Valid Parentheses

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

原文地址:http://blog.csdn.net/zhengsenlie/article/details/39120053

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