Valid Parentheses
Description
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open
brackets must be closed in the correct order.
Sample Test Case
Input: s = "()[]{}"
Output: true
Solution Approach
We use a stack to keep track of opening brackets. For each closing bracket, check if the top of the
stack matches. If not, return false.
Solution Code
class Solution:
def isValid(self, s):
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping:
top = [Link]() if stack else '#'
if mapping[char] != top:
return False
else:
[Link](char)
return not stack
Time Complexity
Time Complexity: O(n), Space Complexity: O(n)