LC 20 - Valid Parentheses
LC 20 - Valid Parentheses
Question
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.
Example 1:
1
2
Input: s = "()"
Output: true
Example 2:
1
2
Input: s = "()[]{}"
Output: true
Example 3:
1
2
Input: s = "(]"
Output: false
Example 4:
1
2
Input: s = "([])"
Output: true
Example 5:
1
2
Input: s = "([)]"
Output: false
Constraints:
1 <= s.length <= 104sconsists of parentheses only'()[]{}'.
Links
Question here and solution here
Solution
concept
Use a stack to keep track the current bracket status. Whenever a matching closing bracket comes in, we can pop the stack.
If it is an opening bracket, we will append to the stack
code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def isValid(self, s: str) -> bool:
stack = []
closeToOpen = { ")" : "(", "]" : "[", "}" : "{" }
for c in s:
if c in closeToOpen:
if stack and stack[-1] == closeToOpen[c]:
stack.pop()
else:
return False
else:
stack.append(c)
return True if not stack else False
Complexity
time: $O(n)$
space: $O(n)$
This post is licensed under CC BY 4.0 by the author.