The problem statement is as follows:
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
If you want to checkout the original problem go here
So first thing you would want to know is what the different parts of a parentheses is
opening = "{[("
closing = "}])"
we are also going to need to know the corresponding opening and closing brackets so we can put use a dictionary.
brackets = {')': '(', '}': '{', ']': '['}
So now we can go through the actual input string and check. If the character is an opening bracket, then we can push it onto a stack.
If it is a closing, we must check if our stack is empty or not. If it is empty, then we can return False.
Otherwise, we check the most recent item we pushed onto the stack and compare it with our current item. If they are matching open and close brackets then we can pop.
for char in s:
if char in opening:
stack.append(char)
elif char in closing:
if len(stack) == 0:
return False
if stack[-1] == brackets[char]:
stack.pop()
else:
return False
return len(stack) == 0
full solution
def isValid(s):
opening = "{[("
closing = "}])"
brackets = {')': '(', '}': '{', ']': '['}
stack = []
for char in s:
if char in opening:
stack.append(char)
elif char in closing:
if len(stack) == 0:
return False
if stack[-1] == brackets[char]:
stack.pop()
else:
return False
return len(stack) == 0
Top comments (2)
in javascript:
It is showing error