A parentheses string is valid if it is empty, if it is `AB` where `A` and `B` are valid, or if it is `(A)` where `A` is valid. You are given a string `s` of `(` and `)`. In one move you may insert a single parenthesis anywhere in the string. Return the minimum number of moves needed to make `s` valid.
A parentheses string is valid if it is empty, if it is AB where A and B are valid, or if it is (A) where A is valid. You are given a string s of ( and ). In one move you may insert a single parenthesis anywhere in the string. Return the minimum number of moves needed to make s valid.
Example 1:
Input: {"s":"())"}
Output: 1
Constraints:
1≤s.length≤1000
s[i] is either '(' or ')'.
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"s":"())"}
s; same colour = matched pair, dashed green = inserted
(
0
)
1
)
2
Scan left to right with two counters: open = '(' still waiting for a partner, added = '(' we had to insert.