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!
Andrew Sologor
· a year ago
func isValid(s1 string) bool { stack := []rune{} for _, c := range s1 { switch c { case '(': stack = append(stack, ')') case '[': stack = append(stack, ']') case '{': stack = append(stack, '}') case ')', ']', '}': if len(stack) == 0 || stack[len(stack) - 1] != c { return false } // remove the last element from the stack stack = stack[:len(stack) - 1] } } return len(stack) == 0 }