-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
70 lines (65 loc) · 1.84 KB
/
main.cpp
File metadata and controls
70 lines (65 loc) · 1.84 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Source: https://leetcode.com/problems/minimum-add-to-make-parentheses-valid
// Title: Minimum Add to Make Parentheses Valid
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A parentheses string is valid if and only if:
//
// - It is the empty string,
// - 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.
//
// You are given a parentheses string `s`. In one move, you can insert a parenthesis at any position of the string.
//
// - For example, if `s = "()))"`, you can insert an opening parenthesis to be `"(**(**)))"` or a closing parenthesis to be `"())**)**)"`.
//
// Return the minimum number of moves required to make `s` valid.
//
// **Example 1:**
//
// ```
// Input: s = "())"
// Output: 1
// ```
//
// **Example 2:**
//
// ```
// Input: s = "((("
// Output: 3
// ```
//
// **Constraints:**
//
// - `1 <= s.length <= 1000`
// - `s[i]` is either `'('` or `')'`.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <string>
using namespace std;
// Count
//
// Count the number of unclosed left parentheses.
// For each right parenthesis, decrease the count.
// If the count is already zero, then we need to add a left parenthesis.
//
// In the end, we also need to add the same number of right parentheses.
class Solution {
public:
int minAddToMakeValid(const string &s) {
int ans = 0;
int count = 0;
for (char ch : s) {
if (ch == '(') {
++count;
} else {
if (count == 0) {
++ans;
} else {
--count;
}
}
}
return ans + count;
}
};