Solved, using stack method of append and pop

This commit is contained in:
Jacob Delgado 2023-09-24 21:27:35 -07:00
parent f5c20bdcca
commit 085299d955
2 changed files with 26 additions and 31 deletions

View 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

View File

@ -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("{[]}"))