Grokking Data Structures & Algorithms for Coding Interviews
0% completed
Solution: Balanced Parentheses
Problem Statement
Given a string s containing (, ), [, ], {, and } characters. Determine if a given string of parentheses is balanced.
A string of parentheses is considered balanced if every opening parenthesis has a corresponding closing parenthesis in the correct order.
Example 1:
Input: String s = "{[()]}";
Expected Output: true
Explanation: The parentheses in this string are perfectly balanced. Every opening parenthesis '{', '[', '(' has a corresponding closing parenthesis '}', ']', ')' in the correct order.
Example 2:
.....
.....
.....
Like the course? Get enrolled and start learning!
Mohammed Dh Abbas
· 2 years ago
class Solution: def isValid(self, s): stack = [] for char in s: if char == '{' or char == '[' or char == '(': stack.append(char) else: popped = stack.pop() if popped == '{' and char != '}': return False elif popped == '[' and char != ']': return False elif popped == '(' and char != ')': return False return len(stack) == 0
Show 1 reply