Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input:s = "()"
Output:true
Example 2:
Input:s = "()[]{}"
Output:true
Example 3:
Input:s = "(]"
Output:false
Example 4:
Input:s = "([])"
Output:true
Example 5:
Input:s = "([)]"
Output:false
Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'.
Solutions
Solution 1: Stack
Thinking
Repeatedly deleting adjacent pairs \(()\), \([]\), and \(\{\}\) until nothing is left is correct, but each pass rescans the string. With \(n \le 10^4\), deeply nested input falls to \(O(n^2)\) and can easily time out.
The bottleneck is that a match is more than two neighboring characters. A later opener must close first, while an earlier one stays open. Once the brackets cross, as in \(([)]\), deleting neighbors cannot reduce the string to empty.
Matching is therefore last-in, first-out: the only legal partner of the current closer is the most recent unmatched opener. A stack keeps those unfinished matches. An opener pushes its closer, so the closer allowed next sits on top, and a closer is compared only with that top. A mismatch means the type or the order is already wrong, and a non-empty stack at the end means some opener never closed.
We use a hash table \(d\) to map each opening bracket to its closing bracket, and a stack \(\textit{stk}\) to store closers that have not been matched yet. Scan \(s\) from left to right. When the current character is an opening bracket, push the corresponding closer from \(d\) onto \(\textit{stk}\). When it is a closing bracket, return false if \(\textit{stk}\) is empty or the popped top is different from that character.
After the scan, return true if \(\textit{stk}\) is empty: every pair has been closed in the right type and order. If the stack still holds a closer, some opening bracket was never matched, so return false.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the length of \(s\).