Balanced Brackets
Difficulty: Easy · Topics: Stack, String · Acceptance: 100.0% of 1 submissions
Difficulty: Easy | Tags: Stack, String
Description
Given a string containing only the characters (, ), {, }, [, and ], determine if the brackets are properly matched and nested.
Implement:
isBalanced(String s) → boolean
Return true if every opening bracket has a corresponding closing bracket of the same type and brackets are properly nested. An empty string is considered balanced.
Examples
Example 1:
Input: "()"
Output: true
Example 2:
Input: "({[]})"
Output: true
Example 3:
Input: "{[}]"
Output: false
Explanation: Brackets are not properly nested.
Example 4:
Input: ""
Output: true
Explanation: Empty string is considered balanced.
Constraints
- 0 ≤ s.length ≤ 104
- s consists only of
(){}[]characters.
Hints
Hint 1
Use a stack: push opening brackets, pop on closing brackets and verify they match.
Hint 2
If the stack is non-empty at the end, there are unmatched opening brackets.