Question Link
Description:#
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.
- Every close bracket has a corresponding open bracket of the same type.
Examples#
Example 1#
1
2
| Input: s = "()"
Output: true
|
Example 2#
1
2
| Input: s = "()[]{}"
Output: true
|
Example 3#
1
2
| Input: s = "(]"
Output: false
|
Constraints#
1 <= s.length <= $10^4$
s
consists of parentheses only '()[]{}'
.
Thoughts#
Solution#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| class Solution:
def isValid(self, s: str) -> bool:
stack = []
l_paren = ['(', '[', '{']
r_paren = [')', ']', '}']
for i in s:
if i in l_paren:
stack.append(i)
if i in r_paren:
if len(stack) == 0:
return False
latest = stack.pop()
if r_paren[l_paren.index(latest)] != i:
return False
if len(stack) > 0:
return False
else:
return True
|