-> 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.
Eg ->
Input: s = "()"
Output: true
class Solution:
def isValid(self, s: str) -> bool:
stack =[]
for i in s:
if i == "(" or i == "{" or i == "[" :
stack.append(i)
elif i == ")" :
if stack and stack[-1]=="(":
stack.pop()
else:
stack.append(i)
elif i == "}" :
if stack and stack[-1]=="{":
stack.pop()
else:
stack.append(i)
elif i == "]" :
if stack and stack[-1]=="[":
stack.pop()
else:
stack.append(i)
if stack:
return False
else:
return True
Top comments (0)