- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_3223.java
50 lines (48 loc) · 1.81 KB
/
_3223.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
packagecom.fishercoder.solutions.fourththousand;
importjava.util.Deque;
importjava.util.HashMap;
importjava.util.LinkedList;
importjava.util.Map;
publicclass_3223 {
publicstaticclassSolution1 {
publicintminimumLength(Strings) {
Map<Character, Integer> map = newHashMap<>();
Deque<Character> stack = newLinkedList<>();
for (inti = 0; i < s.length(); i++) {
charc = s.charAt(i);
if (!map.containsKey(c) || map.get(c) < 2) {
map.put(c, map.getOrDefault(c, 0) + 1);
stack.addLast(c);
} else {
Deque<Character> tmpStack = newLinkedList<>();
intremovedCount = 0;
while (!stack.isEmpty()) {
Characterlast = stack.pollLast();
if (last == c) {
map.put(c, map.get(c) - 1);
if (map.get(c) == 0) {
map.remove(c);
}
removedCount++;
if (removedCount == 2) {
break;
}
} else {
tmpStack.addLast(last);
}
}
while (!tmpStack.isEmpty()) {
stack.addLast(tmpStack.pollLast());
}
stack.addLast(c);
map.put(c, map.getOrDefault(c, 0) + 1);
}
}
StringBuildersb = newStringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pollFirst());
}
returnsb.toString().length();
}
}
}