【leetcode】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:
    # @return a boolean
    def isValid(self, s):
        sta = []
        for i in s:
            if i in ['(','[','{']:
                sta.append(i)
            elif i == ')':
                if len(sta) < 1 or sta[len(sta)-1] != '(':
                    return False
                else:
                    sta.pop()
            elif i == ']':
                if len(sta) < 1 or sta[len(sta)-1] != '[':
                    return False
                else:
                    sta.pop()
            else:
                if len(sta) < 1 or sta[len(sta)-1] != '{':
                    return False
                else:
                    sta.pop()
        if len(sta) != 0:
            return False
        return True
posted @ 2015-01-19 14:47  mrbean  阅读(208)  评论(0编辑  收藏  举报