- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1541.java
61 lines (59 loc) · 2.23 KB
/
_1541.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
packagecom.fishercoder.solutions.secondthousand;
importjava.util.Stack;
publicclass_1541 {
publicstaticclassSolution1 {
publicintminInsertions(Strings) {
Stack<Character> stack = newStack<>();
intinsertionsNeeded = 0;
for (inti = 0; i < s.length(); i++) {
charc = s.charAt(i);
if (c == '(') {
if (stack.isEmpty()) {
stack.add(c);
} else {
if (stack.peek() == ')') {
// in this case, we need to add one more ')' to get two consecutive
// right paren, then we could pop the one ')' and one '(' off the stack
insertionsNeeded++;
stack.pop();
stack.pop();
stack.add(c);
} else {
stack.add(c);
}
}
} elseif (c == ')') {
if (stack.isEmpty()) {
// in this case, we need to add one '(' before we add this ')' onto this
// stack
insertionsNeeded++;
stack.add('(');
stack.add(c);
} else {
if (stack.peek() == ')') {
// in this case, we could pop the one ')' and one '(' off the stack
stack.pop();
stack.pop();
} else {
stack.add(c);
}
}
}
}
if (stack.isEmpty()) {
returninsertionsNeeded;
} else {
while (!stack.isEmpty()) {
charpop = stack.pop();
if (pop == '(') {
insertionsNeeded += 2;
} else {
insertionsNeeded++;
stack.pop();
}
}
returninsertionsNeeded;
}
}
}
}