您的位置:首页 > 编程语言 > Go语言

[勇者闯LeetCode] 20. Valid Parentheses

2017-03-10 23:47 351 查看

[勇者闯LeetCode] 20. Valid Parentheses

Description

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.

Information

Tags: Stack | String

Difficulty: Easy

Solution

用栈存储需要遇到的右括号。扫描字符串时遇到左括号则其对应的右括号入栈,遇到右括号则出栈并判断两个右括号是否相同,若不相同则返回
false
。扫描结束后,若栈内还有元素,则返回
false


class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
l = {"(": ")", "[": "]", "{": "}"}
ans = []
for x in s:
if x in l:
ans.append(l[x])
elif (len(ans) == 0 or ans.pop() != x):
return False
return False if len(ans) > 0 else True
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm leetcode