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 1:
Input: "())" Output: 1
Example 2:
Input: "(((" Output: 3
Example 3:
Input: "()" Output: 0
Example 4:
Input: "()))((" Output: 4
Note:
S.length <= 1000
S
 only consists ofÂ'('
 andÂ')'
 characters.
Solution: Counting
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Author: Huahua class Solution { public: int minAddToMakeValid(string S) { int l = 0; int m = 0; for (char c : S) { if (c == '(') ++l; if (c == ')' && l > 0) { --l; ++m; } } return S.size() - m * 2; } }; |