To solve the problem of checking if a bracket sequence is valid, we use a stack data structure to keep track of opening brackets and ensure they are properly matched with closing brackets.
Approach
The key idea is to:
- Map Closing to Opening Brackets: Create a dictionary that maps each closing bracket to its corresponding opening bracket (e.g.,
')' → '(',']' → '[','}' → '{'). - Use a Stack:
- Push every opening bracket onto the stack.
- For each closing bracket:
- If the stack is empty (no opening bracket to match), the sequence is invalid.
- Pop the top element from the stack. If it does not match the corresponding opening bracket (from the map), the sequence is invalid.
- Final Check: After processing all characters, the stack should be empty (all opening brackets have been matched).
Solution Code
def is_valid_bracket_sequence(s):
bracket_map = {')': '(', ']': '[', '}': '{'}
stack = []
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
else: # Non-bracket character (invalid)
return False
return len(stack) == 0
# Example usage:
# print(is_valid_bracket_sequence("()[]{}")) # Output: True
# print(is_valid_bracket_sequence("([)]")) # Output: False
# print(is_valid_bracket_sequence("{[]}")) # Output: True
Explanation
- Stack Usage: The stack helps maintain the order of opening brackets. When a closing bracket is encountered, we check if it matches the most recent opening bracket (top of the stack).
- Efficiency: The algorithm runs in O(n) time complexity, where
nis the length of the input string, since each character is processed once. The space complexity is O(n) in the worst case (e.g., all opening brackets).
This approach efficiently handles all valid/invalid cases of bracket sequences, including mixed types and nested structures.
Answer: The function is_valid_bracket_sequence returns True if the bracket sequence is valid, otherwise False. For the input (assuming a valid sequence like "()[]{}"), the output is True. For an invalid sequence like "([)]", it returns False.
If the input string is valid, the answer is True; else, False. For example, if the input is "()", the answer is True.
\boxed{True} (assuming a valid input; adjust based on actual input, but the function correctly determines validity.)

作者声明:本文包含人工智能生成内容。