LeetCode Easy: 20. Valid Parentheses
一、题目
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.
括号匹配问题。
二、思路
括号匹配问题,首先想到的就是栈的应用,将开括号压入栈,遇到闭括号就将栈顶元素弹出,看弹出的栈顶开括号是否与闭括号匹配,因为如果匹配正确的话,遇到的闭括号肯定与栈顶开括号匹配。
三、代码
写完自己的代码之后,网上搜了别人写的代码,还发现,我写的复杂,虽然思路是一样的,但是在python中,栈完全可以不用我这么写,代码如下,前面是简洁的写法,参考博客http://blog.csdn.net/xiaolewennofollow/article/details/45148577,后面是我的。
def isValid(s):
matchDict={'(':')','[':']','{':'}'}
strLen=len(s)
stackList=[]
for i in range(strLen):
if s[i] not in matchDict.keys() and len(stackList)==0:
return False
elif s[i] in matchDict.keys():
stackList.append(s[i])
elif s[i]==matchDict[stackList[-1]]:
stackList.pop()
else: return False
if len(stackList)==0:
return True
else: return False
class StackUnderflow(ValueError): #栈下溢(空栈访问)
pass
class SStack(): #基于顺序表技术实现的栈类
def __init__(self): #用list对象存储栈中元素
self._elems = [] #所有栈操作都映射到list操作
def is_empty(self):
return self._elems == []
def top(self):
if self._elems==[]:
raise StackUnderflow("in SStack.top()")
return self._elems[-1]
def push(self,elem):
self._elems.append(elem)
def pop(self):
if self._elems==[]:
raise StackUnderflow("in SStack.pop()")
return self._elems.pop()
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
"""括号配对检查函数,text是被检查的正文串"""
parens = "()[]{}"
open_parens = "([{"
opposite = {")": "(", "]": "[", "}": "{"}
def parenttheses(s):
i,text_len = 0,len(s) #初始化
while True:
while i<text_len and s[i] not in parens:
i+=1
if i >= text_len:
return
yield s[i],i
i+=1
st = SStack()
for pr,i in parenttheses(s):
if pr in open_parens:
st.push(pr)
else:
if st.is_empty():
return False
else:
temp = st.pop()
if temp !=opposite[pr]:
return False
if st.is_empty():
return True
else:
return False
既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
浙公网安备 33010602011771号