设为首页 加入收藏

TOP

Leetcode 栈 Valid Parentheses
2015-07-20 17:44:13 来源: 作者: 【 】 浏览:1
Tags:Leetcode Valid Parentheses

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

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Lua和C++交互总结(很详细) 下一篇LeetCode-Balanced Binary Tree

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·常用meta整理 | 菜鸟 (2025-12-25 01:21:52)
·SQL HAVING 子句:深 (2025-12-25 01:21:47)
·SQL CREATE INDEX 语 (2025-12-25 01:21:45)
·Shell 传递参数 (2025-12-25 00:50:45)
·Linux echo 命令 - (2025-12-25 00:50:43)