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; } }; |