Stack•Medium
Balanced Parentheses
Balanced Parentheses Algorithm
Matching bracket problems are classical compiler syntax checking applications.
Algorithm Logic
- Scan Expression: Iterate through each character in the string sequence from left to right.
- Push Opening Brackets: If the character is an opening bracket (
(,{,[), push it onto the stack. - Handle Closing Brackets: If the character is a closing bracket (
),},]):- Check if stack is empty. If empty, the brackets are unbalanced (closing bracket without opening).
- Pop the top bracket off the stack and check if it is of matching type (e.g.
(matches)). If not, brackets are unbalanced.
- Final Check: After scanning the entire string, the stack should be empty. If it is not, some opening brackets were left unmatched, making it unbalanced.