-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path1541.Minimum-Insertions-to-Balance-a-Parentheses-String.java
61 lines (51 loc) · 1.71 KB
/
1541.Minimum-Insertions-to-Balance-a-Parentheses-String.java
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
// https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/
// algorithms
// Medium (38.44%)
// Total Accepted: 4,831
// Total Submissions: 12,569
class Solution {
private static final char LEFT_BRACKETS = '(';
private static final char RIGHT_BRACKETS = ')';
public int minInsertions(String s) {
int len = s.length();
LinkedList<Integer> left = new LinkedList<>();
LinkedList<Integer> doubleRight = new LinkedList<>();
LinkedList<Integer> singleRight = new LinkedList<>();
for (int i = 0; i < len; i++) {
if (s.charAt(i) == LEFT_BRACKETS) {
left.offerLast(i);
} else {
if (i < len - 1 && s.charAt(i + 1) == RIGHT_BRACKETS) {
if (!left.isEmpty()) {
left.pollLast();
} else {
doubleRight.offerLast(i);
}
i++;
} else {
singleRight.offerLast(i);
}
}
}
int res = doubleRight.size();
if (!left.isEmpty()) {
while (!singleRight.isEmpty()) {
int idx = singleRight.peekLast();
while (!left.isEmpty() && left.peekLast() > idx) {
left.pollLast();
res += 2;
}
if (!left.isEmpty()) {
res++;
left.pollLast();
singleRight.pollLast();
} else {
break;
}
}
}
res += left.size() * 2;
res += singleRight.size() * 2;
return res;
}
}