![]() |
VOOZH | about |
Given a string s containing three types of brackets {}, () and []. Determine whether the Expression are balanced or not.
An expression is balanced if each opening bracket has a corresponding closing bracket of the same type, the pairs are properly ordered and no bracket closes before its matching opening bracket.
Example:
Input: s = "[{()}]"
Output: true
Explanation: All the brackets are well-formed.Input: s = "([{]})"
Output: false
Explanation: The expression is not balanced because there is a closing ']' before the closing '}'.
Table of Content
We use a stack to ensure that every opening has a matching closing. Each opening is pushed onto the stack. When a closing appears, we check if the stack has a corresponding opening to pop; if not, the string is unbalanced. After processing the entire string, the stack must be empty for it to be considered balanced.
Illustration:
true
Instead of using an external stack, we can simulate stack operations directly on the input string by modifying it in place. A variable top is used to track the index of the last unmatched opening bracket. Whenever an opening bracket is found, it is placed at the next top position. For a closing bracket, we check if it matches the character at top. If it does, we simply decrement top; otherwise, the string is unbalanced. In the end, if top is -1, all brackets are matched and the string is balanced.
Note: Strings are immutable in Java, Python, C#, and JavaScript. Therefore, we cannot modify them in place, making this approach unsuitable for these languages.
true