Solved, using stack method of append and pop
This commit is contained in:
parent
f5c20bdcca
commit
085299d955
26
NeetCodeRoadmap/Stack/20_Valid_Parenthesis.py
Normal file
26
NeetCodeRoadmap/Stack/20_Valid_Parenthesis.py
Normal file
@ -0,0 +1,26 @@
|
||||
def isValid(s):
|
||||
"""
|
||||
:type s: str
|
||||
:rtype: bool
|
||||
"""
|
||||
stack = [] # only use append and pop
|
||||
pairs = {
|
||||
'(': ')',
|
||||
'{': '}',
|
||||
'[': ']'
|
||||
}
|
||||
for bracket in s:
|
||||
if bracket in pairs:
|
||||
stack.append(bracket)
|
||||
elif len(stack) == 0 or bracket != pairs[stack.pop()]: # Checks for corresponding dictionary value based on previous closing bracket
|
||||
return False
|
||||
print(stack)
|
||||
return len(stack) == 0
|
||||
|
||||
|
||||
|
||||
# print(isValid("()")) # true
|
||||
print(isValid("()[]{}")) # true
|
||||
print(isValid("(]")) # false
|
||||
print(isValid("([)]")) # false
|
||||
print(isValid("{[]}")) # true
|
||||
@ -1,31 +0,0 @@
|
||||
def isValid(s):
|
||||
"""
|
||||
:type s: str
|
||||
:rtype: bool
|
||||
"""
|
||||
pervious = ""
|
||||
openBracket = ['(', '{', '[']
|
||||
bracketPairs = ['()', '{}', '[]']
|
||||
pairs = None
|
||||
|
||||
for x in s:
|
||||
if x in openBracket:
|
||||
previous = x
|
||||
else:
|
||||
# print(previous+x)
|
||||
if (previous+x) in bracketPairs:
|
||||
pairs = True
|
||||
else:
|
||||
return False
|
||||
return pairs
|
||||
|
||||
print(isValid("()"))
|
||||
print(isValid("()[]{}"))
|
||||
print(isValid("(]"))
|
||||
print(isValid("([)]"))
|
||||
print(isValid("{[]}"))
|
||||
print(isValid("{[]}"))
|
||||
print(isValid("{[]}"))
|
||||
print(isValid("{[]}"))
|
||||
print(isValid("{[]}"))
|
||||
print(isValid("{[]}"))
|
||||
Loading…
Reference in New Issue
Block a user