forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.cpp
39 lines (30 loc) · 763 Bytes
/
main2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/// Source : https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/description/
/// Author : liuyubobobo
/// Time : 2018-10-14
#include <iostream>
#include <stack>
using namespace std;
/// Using balance to record the stack top '(' size
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
int minAddToMakeValid(string S) {
int res = 0, bal = 0;
for(char c: S)
if(c == '(')
res ++, bal ++;
else{
if(bal)
res --, bal --;
else
res ++, bal = 0;
}
return res;
}
};
int main() {
cout << Solution().minAddToMakeValid("()))((") << endl;
// 4
return 0;
}