题目
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.采用栈机制,对于每个进栈元素都与栈顶元素进行匹配,若匹配成功,这栈顶元素弹出,若匹配不成功,则进栈
Pyhon实现:
# -*- coding:utf-8 -*-
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
brackets=[]
for i in range(0,s.__len__()):
pipei=False
if len(brackets)!=0:
b=brackets.pop()
if b=='(':
if s[i]==')':
pipei=True
elif b=='{':
if s[i]=='}':
pipei=True
elif b=='[':
if s[i]==']':
pipei=True
if pipei==False:
brackets.append(b)
brackets.append(s[i]);
else:
brackets.append(s[i])
if len(brackets)==0:
return True
else:
return False
if __name__=="__main__":
s=Solution()
res=s.isValid("{[)(]}")
print(res)
本文介绍了一种使用栈来判断括号是否正确配对的方法。通过遍历字符串中的括号,并利用栈的数据结构特性来实现括号的有效匹配。文章提供了一个Python实现的例子。
681

被折叠的 条评论
为什么被折叠?



