20. Valid Paranthesis
Given a string
scontaining 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.
- Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
def isValid(self, s: str) -> bool:
symlis = []
for ch in s:
if ch == '{' or ch == '(' or ch=='[':
symlis.append(ch)
elif ch == '}' and symlis:
if symlis[-1]=='{':
symlis.pop()
else:
return False
elif ch == ']' and symlis:
if symlis[-1]=='[':
symlis.pop()
else:
return False
elif ch == ')' and symlis:
if symlis[-1]=='(':
symlis.pop()
else:
return False
else:
return False
if len(symlis)==0:
return True
def isValid(s):
stack = []
bracket_pairs = {')': '(', '}': '{', ']': '['}
for char in s:
if char in bracket_pairs.values():
stack.append(char)
elif char in bracket_pairs.keys():
if not stack or bracket_pairs[char] != stack.pop():
return False
else:
return False
return not stack