The problem. Given a string s containing only the characters (, ), [, ], { and }, decide whether it is valid: every opening bracket is closed by the same type of bracket, and brackets close in the correct order — the most recently opened bracket closes first.
Input: s = "()[]{}" Output: true
Input: s = "(]" Output: false
Input: s = "([)]" Output: false
Input: s = "{[]}" Output: trueCounting isn't enough: ([)] has one of each bracket, yet it's invalid. What matters is the order: a closing bracket must match the most recent bracket that is still open.
Members only · free account
The rest of this lesson, with 5 more sections, 2 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++, opens with a free account.
Not ready yet? The Arrays course is free to read, no account needed.
In the rest of this lesson