Given a string consisting only of '(', ')', '{', '}', '[', ']', check whether the string is valid.
A valid string must satisfy:
- An opening bracket must be closed with a closing bracket of the same type.
- Opening parentheses must be closed in the correct order.
Note that an empty string is considered a valid string.
Algorithm ideas: the use of stack
python code
class Solution:
def isValid(self, s: str) -> bool:
t = []
for i in s:
if i == "(" or i == "{" or i == "[":
t.append(i)
elif i == ")":
if len(t) == 0 or t.pop() != "(":
return False
elif i == "}":
if len(t) == 0 or t.pop() != "{":
return False
elif i == "]":
if len(t) == 0 or t.pop() != "[":
return False
if len(t) == 0:
return True
else:
return False