您的位置:首页 > 其它

lintcode: 有效的括号序列

2015-10-17 20:14 316 查看
题目:

有效的括号序列

给定一个字符串所表示的括号序列,包含以下字符:
'(', ')'
,
'{'
,
'}'
,
'['
and
']'
, 判定是否是有效的括号序列。

样例

括号必须依照
"()"
顺序表示,
"()[]{}"
是有效的括号,但
"([)]"
则是无效的括号。

挑战

O(n)的时间,n为括号的个数

解题:

数据结构上面讲过的,碰到"[","(","{"入栈,碰到"]"检测栈顶是不是"[",是出栈,不是返回false,对")","}"同理了。开始我用LinkedList实现栈,没有搞好,然后网上看到java有Stack的。import.util.Stack,然后想着写简单点,有错了一路。。。

Java程序:

class Solution:
# @param {string} s A string
# @return {boolean} whether the string is a valid parentheses
def isValidParentheses(self, s):
# Write your code here
stack = []
slen = len(s)
for elm in s:
if elm=='(' or elm == '[' or elm == '{':
stack.append(elm)
elif elm==')' or elm == ']' or elm == '}':
if len(stack)==0:
return False
top = stack.pop()
if top == '(' and elm== ')':
continue
elif top == '[' and elm ==']':
continue
elif top == '{' and elm == '}':
continue
else:
return False
if len(stack)==0:
return True
else:
return False


View Code
总耗时: 409 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: