Given a string S of ‘(‘ and ‘)’ parentheses, we add the minimum number of parentheses ( ‘(‘ or ‘)’, and in any positions ) so that the resulting parentheses string is valid.
Formally, a parentheses string is valid if and only if:
It is the empty string, or
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.
Example
Input: “()))((“
Output: 4
My solution:
1 |
|
Tricky
1 |
class (object): |
Analyse
the key is on the balance of parentheses.
there are two cases:
- the number of ‘(‘, l, is more than ‘)’, r.
- r>l
In the fist case, we need to record l and when meeting ‘)’ just subtract from l. When l become 0 or negative, it means we jump to the second case.
In the second case, we can add the superfluous ‘)’ to the final result because it is impossible to get the corresponding ‘(‘. And when it meets ‘(‘,it jumps to case 1 again.
近期评论