Easy-题目47:20. Valid Parentheses

转载 2016年05月30日 20:39:55

题目原文:
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.
题目大意:
给出一个括号字符串,判断括号是否正确匹配。
题目分析:
本题考查堆栈的使用,遇到左边的括号全部入栈,遇到右边的括号则看栈顶的括号是不是对应的左括号,如是则弹出,如不是则返回错误。如果整个括号字符串扫完之后栈恰好为空,则是合法匹配。
源码:(language:python)

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack=[]
        for c in s:
            if c in ['(','[','{']:
                stack.append(c)
            else:
                if(len(stack)==0):
                    return False
                top=stack[len(stack)-1]
                if ((c == ')' and top=='(') or (c == ']' and top=='[') or (c == '}' and top == '{')):
                    stack.pop()
                else:
                    return False

        return len(stack)==0

成绩:
43ms,beats 55.57%,众数40ms,27.91%

LeetCode OJ 20 Valid Parentheses [Easy]

LeetCode OJ 20 Valid Parentheses 题目描述: Given a string containing just thecharacters '(', ')', '{', ...

Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]

Valid Parentheses [Difficulty: Easy]: Given a string containing just the characters , determine if ...

Leetcode笔记整理—easy篇—Valid Parentheses

**Valid Parentheses**问题简介:Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ...

leetcode20:Valid Parentheses

Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and']',...
  • GODBAR
  • GODBAR
  • 2016年12月22日 21:58
  • 174

LeetCode 20. Valid Parentheses 辅助数据结构栈

Valid Parentheses 题意 注意 思路 代码 结果20. Valid Parentheses Given a string containing just the character...

Leetcode20: Valid Parentheses

这题的答题思路基本是对了,用字典来解决,不过,还是没有对stack的应用太熟悉,还需练习。 class Solution(object): def isValid(self, s):...

LeetCode20. Valid Parentheses

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the inpu...

20. Valid Parentheses (括号匹配)

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the in...

LeetCode 20 Valid Parentheses (C,C++,Java,Python)

Problem: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', deter...

[leetcode]20. Valid Parentheses(java)

问题形容: 题目:有效括号 description: Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Easy-题目47:20. Valid Parentheses
举报原因:
原因补充:

(最多只允许输入30个字)