Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([])"
Output: true
Constraints:
1 <= s.length <= 104
s
consists of parentheses only '()[]{}'
.This problem checks if a given string containing parentheses ()
, []
, and {}
is valid. A valid string means:
The most efficient approach uses a stack data structure. The algorithm iterates through the input string:
Opening Bracket: If an opening bracket ((
, [
, {
) is encountered, it's pushed onto the stack. The stack keeps track of unmatched opening brackets.
Closing Bracket: If a closing bracket is encountered:
false
is returned.(
and ]
), the string is invalid, and false
is returned.End of String: After iterating through the entire string:
true
is returned.false
is returned.class Solution:
def isValid(self, s: str) -> bool:
stack = []
bracket_map = {')': '(', '}': '{', ']': '['}
for char in s:
if char in bracket_map.values(): # Opening bracket
stack.append(char)
elif char in bracket_map.keys(): # Closing bracket
if not stack or stack.pop() != bracket_map[char]:
return False # Unmatched or stack empty
else:
return False #Invalid character
return not stack # True if stack is empty (all brackets matched)
This Python code efficiently implements the stack-based solution. The bracket_map
dictionary provides a quick lookup for matching brackets. The if not stack or stack.pop() != bracket_map[char]
line elegantly handles both the empty stack and mismatch conditions.
The implementations in other languages (Java, C++, Go, TypeScript, Rust, JavaScript, C#, Ruby, PHP) follow the same logic, adapting the syntax and data structures to each language's specifics, but the core algorithm remains the same.