Balanced Parentheses Checker
This solution uses a stack data structure to check if the parentheses in a given string are balanced. The idea is to push every opening parenthesis onto the stack and pop the stack for every closing parenthesis. If the stack is empty when encountering a closing parenthesis or if there are items left in the stack at the end, the parentheses are not balanced.
Code (Python)
def is_balanced(s: str) -> bool:
"""
Checks if the parentheses in a given string are balanced.
Args:
s (str): The input string containing parentheses.
Returns:
bool: True if the parentheses are balanced, False otherwise.
"""
stack = []
parentheses_map = {')': '(', '}': '{', ']': '['}
for char in s:
# If the character is an opening parenthesis, push it onto the stack
if char in parentheses_map.values():
stack.append(char)
# If the character is a closing parenthesis, check if the stack is empty or the top of the stack does not match
elif char in parentheses_map.keys():
if not stack or stack.pop() != parentheses_map[char]:
return False
# If the stack is empty after processing the entire string, the parentheses are balanced
return not stack
# Example usage
if __name__ == "__main__":
test_cases = [
("((()))", True),
("(()", False),
("({[]})", True),
("({[}])", False),
("hello world", True), # No parentheses, so considered balanced
("(hello world)", True),
("(hello (world))", True),
("(hello (world)", False)
]
for s, expected in test_cases:
result = is_balanced(s)
print(f"String: {s}, Balanced: {result}, Expected: {expected}")
assert result == expected, f"Test case failed for string: {s}"
print("All test cases passed.")
Explanation
-
We initialize an empty stack stack to store the opening parentheses encountered so far.
-
A dictionary parentheses_map is created to map closing parentheses to their corresponding opening ones.
-
We iterate over each character char in the input string s.
-
If char is an opening parenthesis (i.e., a value in parentheses_map), we push it onto the stack.
-
If char is a closing parenthesis (i.e., a key in parentheses_map), we check two conditions:
- If the stack is empty (
not stack), it means there's no matching opening parenthesis, so we return False.
- If the top of the stack (
stack.pop()) does not match the expected opening parenthesis for char (parentheses_map[char]), we return False.
-
After processing all characters in the string, we check if the stack is empty (not stack). If it is, all parentheses were properly matched and balanced, so we return True. Otherwise, there are unmatched opening parentheses, and we return False.
Time Complexity: O(n), where n is the length of the string, because we process each character once.
Space Complexity: O(n), for the stack in the worst-case scenario (e.g., a string of only opening parentheses). However, in practice, it will be much less if the string has balanced or nearly balanced parentheses.