Balanced Parentheses Checker
Write a function that takes a string containing only parentheses (characters ( and )), and determine if the string is balanced. A string is balanced if it consists of pairs of matching parentheses in the correct order. For example, () and (()) are balanced, but (, ), and (() are not.
[ "()" ]
Explanation. The string `()` contains one pair of matching parentheses.
[ "(())" ]
Explanation. The string `(())` contains two nested pairs of matching parentheses.
[ "(()" ]
Explanation. The string `(()` contains an unmatched `(`.
[ "())(" ]
Explanation. The string `())(` has parentheses that are closed before being opened.
[ "((((()))))" ]
Explanation. The string has multiple nested pairs that are all correctly matched.
[ "()()" ]
Explanation. The string contains two independent matching pairs.
[ "(((" ]
Explanation. The string contains three unmatched `(`.
[ "))))" ]
Explanation. The string contains three unmatched `)`.
Follow-up: Is there a way to extend this function to handle other types of brackets such as `{}`, `[]`?
The input string will only contain the characters `(` and `)`. It can be empty.
- Views
- 2