Check for balanced parentheses in...
Check for balanced parentheses in...
To check for balanced parentheses in linear time using constant space, you can use a counter-based approach. This method avoids the use of a stack, which typically requires O(n) space, and instead uses a few integer variables to keep track of the balance of parentheses. Here is a step-by-step explanation and implementation in Python:
def is_balanced_parentheses(s: str) -> bool:
# Initialize counters for different types of parentheses
round_count = 0
square_count = 0
curly_count = 0
for char in s:
if char == '(':
round_count += 1
elif char == ')':
round_count -= 1
elif char == '[':
square_count += 1
elif char == ']':
square_count -= 1
elif char == '{':
curly_count += 1
elif char == '}':
curly_count -= 1
# Check if any counter goes negative
if round_count < 0 or square_count < 0 or curly_count < 0:
return False
# Final check to ensure all counters are zero
return round_count == 0 and square_count == 0 and curly_count == 0
# Example usage
print(is_balanced_parentheses("({[]})")) # Output: True
print(is_balanced_parentheses("({[})")) # Output: False
round_count
, square_count
, and curly_count
are used to track the balance of ()
, []
, and {}
respectively.s
.senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào