The task is to determine if a given string of parentheses is balanced. A string is considered balanced if every opening parenthesis has a corresponding closing parenthesis in the correct order. For example, the string “({[]})” is valid, while “({[)]}” is not.
def is_balanced(s):
stack = []
pairs = {')': '(', '}': '{', ']': '['}
for char in s:
if char in pairs.values():
stack.append(char)
elif char in pairs.keys():
if not stack or stack.pop() != pairs[char]:
return False
return not stack
# Example usage
print(is_balanced("({[]})")) # True
print(is_balanced("({[)]}")) # False
The function is_valid_parentheses
takes a string s
as input and returns a boolean indicating whether the parentheses in the string are balanced. Here is a breakdown of the code –
- Initialization: A stack is initialized to keep track of opening symbols, and a dictionary is created to define pairs of matching symbols.
- Iteration: The function iterates through each character in the input string.
- Push Opening Symbols: If the character is an opening symbol, it is pushed onto the stack.
- Check Closing Symbols: If the character is a closing symbol, the function checks if it matches the most recent opening symbol from the stack.
- Return Result: Finally, the function returns
True
if all symbols are balanced (i.e., the stack is empty) andFalse
otherwise.