https://leetcode.com/problems/valid-parentheses/
要用到stack。 参考http://www.cnblogs.com/zuoyuan/p/3779772.html
正确code:
class Solution:
# @return a boolean
def isValid(self, s):
stack = []
for i in range(len(s)):
if s[i] == '(' or s[i] == '[' or s[i] == '{':
stack.append(s[i])
if s[i] == ')':
if stack == [] or stack.pop() != '(':
return False
if s[i] == ']':
if stack == [] or stack.pop() != '[':
return False
if s[i] == '}':
if stack == [] or stack.pop() != '{':
return False
if stack:
return False
else:
return True
my code:(不能过leetcode,供自己总结)
思路是用dict,再来判断是否match。但”([)]”这种case过不了,所以题目要求应该是括号严格match,左括号与右括号之间不能有其他括号。
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
help = {'(':')','[':']','{':'}'}
if not s: return True
mydict = {}
for i in xrange(len(s)):
if s[i] in mydict:
mydict[s[i]].append(i)
else:
mydict[s[i]] = [i]
for k,v in help.items():
if (k in mydict) and (v not in mydict):
return False
elif (v in mydict) and (k not in mydict):
return False
elif (v not in mydict) and (k not in mydict):
continue
else:
list1 = mydict[k]
list2 = mydict[v]
if len(list1) != len(list2):
return False
elif min(list2) <= min(list1) or max(list2) <= max(list1):
return False
return True