You get a string input made only of brackets: ( ), [ ] and { }. Return true if the brackets are properly matched, false if not.
Properly matched means:
- Every opening bracket is closed later by a bracket of its own kind.
- A bracket opened later is closed first. Pairs sit inside each other and never cross.
- Every closing bracket closes a bracket opened before it.
Example 1:
Input: input = "{()[]}"
Output: true
Explanation: () and [] both sit inside the {} pair.
Example 2:
Input: input = "{[(])}"
Output: false
Explanation: The ] comes while the ( is still open.
The ( and [ pairs cross.
Example 3:
Input: input = "(()" Output: false Explanation: One ( is never closed.
Constraints:
inputhas 1 to 7,000 characters.- Every character is one of the six brackets.
Note:
Your algorithm should run in O(n) time and use O(n) extra space.
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
