Title description:
Given a string consisting only of '(', ')', '{', '}', '[', ']', check whether the string is valid.
A valid string needs to satisfy:
the opening parenthesis must be closed with the same type of closing parenthesis.
Opening parentheses must be closed in the correct order.
Note that an empty string is considered a valid string.
Example one:
Input: "()"
Output: true
Example two:
Input: “()[]{}”
Output: true
Example three:
Input: "(]"
Output: false
Example four:
Input: “([)]”
Output: false
Example five:
Input: “{[]}”
Output: true
Problem-solving ideas:
class Solution:
def isValid(self, s: str) -> bool:
output = []
label = {')':'(', '}':'{', ']':'['}
for idx in range(len(s)):
if s[idx] in ['(', '{', '[']:
output.append(s[idx])
elif s[idx] in [')', '}', ']'] and len(output) == 0:
return False
elif s[idx] in [')', '}', ']'] and label[s[idx]] == output[-1]:
output.pop()
else:
return False
if len(output) != 0:
return False
else:
return True
Performance analysis: