Given a string s containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid.
A string is considered 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.
Constraints:
1 <= s.length <= 10^4sconsists only of '(', ')', '{', '}', '[', ']'
Example 1:
Input: s = "({[]})"
Output: true
Solution
Approach: Using a Stack
This problem can be efficiently solved using a stack data structure. The core idea is to keep track of opening brackets encountered and then match them with their corresponding closing brackets.
- Initialize an empty stack to store opening brackets.
- Define a map or dictionary to store the relationships between closing brackets and their corresponding opening brackets (e.g.,
')': '(','}' : '{',']' : '['). - Iterate through each character in the input string
s:- If the character is an opening bracket (
(,{,[), push it onto the stack. - If the character is a closing bracket (
),},]):- Check if the stack is empty. If it is, there's no matching opening bracket for the current closing bracket, so the string is invalid.
- Pop the top element from the stack.
- Compare the popped element with the expected opening bracket for the current closing bracket (using our map). If they do not match, the string is invalid.
- If the character is an opening bracket (
- After iterating through the entire string, if the stack is empty, all brackets were correctly matched, and the string is valid. Otherwise, there are unmatched opening brackets, and the string is invalid.
Python Code:
class Solution:
def isValid(self, s: str) -> bool:
stack = []
# Map closing brackets to their corresponding opening brackets
bracket_map = {
')': '(',
'}': '{',
']': '['
}
for char in s:
if char in bracket_map.values(): # It's an opening bracket
stack.append(char)
elif char in bracket_map.keys(): # It's a closing bracket
# If stack is empty or top element doesn't match expected open bracket
if not stack or stack.pop() != bracket_map[char]:
return False
# For any other characters (though problem constraints limit to only brackets), do nothing
# If the stack is empty, all opening brackets were matched
return not stack