Balanced or Not
Given a string consisting only of parentheses ( and ), determine if the string is balanced. A string is balanced if every opening parenthesis ( has a corresponding closing parenthesis ) and the pairs are properly nested.
[ "(())" ]
Explanation. The string has equal number of opening and closing parentheses and they are properly nested.
[ "(()" ]
Explanation. There is an unmatched opening parenthesis.
[ "())" ]
Explanation. There is an unmatched closing parenthesis.
[ "((()))" ]
Explanation. All parentheses are matched and properly nested.
[ ")(" ]
Explanation. The parentheses close before they open.
[ "()()()" ]
Explanation. All opening parentheses have a corresponding closing parenthesis.
Follow-up: Can you extend this solution to handle other types of brackets such as `{}`, `[]`?
The input string will only contain the characters `(` and `)`. The length of the string will be at most 100 characters.
- Views
- 2