-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCandyCrush1D.java
91 lines (77 loc) · 2.55 KB
/
CandyCrush1D.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.util.ArrayDeque;
import java.util.Deque;
/**
* LeetCode
* CandyCrush - 1D
* https://leetcode.com/discuss/interview-question/380650/Bloomberg-or-Phone-Screen-or-Candy-Crush-1D
* #Medium #Stack #CandyCrush
*/
/*
def candy_crush(input):
if not input:
return input
stack = []
stack.append([input[0], 1])
for i in range(1, len(input)):
if input[i] != input[i-1]:
if stack[-1][1] >= 3:
stack.pop()
if stack and stack[-1][0] == input[i]:
stack[-1][1] += 1
else:
stack.append([input[i], 1])
else:
stack[-1][1] += 1
# handle end
if stack[-1][1] >= 3:
stack.pop()
out = []
for ltrs in stack:
out += ltrs[0] * ltrs[1]
return ''.join(out)
print(candy_crush("aaaabbbc")) #c
print(candy_crush("aabbbacd")) #cd
print(candy_crush("aabbccddeeedcba")) #blank expected
print(candy_crush("aabbbaacd")) #cd
print(candy_crush("dddabbbbaccccaax")) #x
*/
public class CandyCrush1D {
public static void main(String[] args) {
CandyCrush1D sol = new CandyCrush1D();
System.out.println(sol.candyCrush("aaaabbbc")); // c
System.out.println(sol.candyCrush("aabbbacd")); // cd
System.out.println(sol.candyCrush("aabbccddeeedcba")); // #blank expected
System.out.println(sol.candyCrush("aabbbaacd")); // cd
System.out.println(sol.candyCrush("dddabbbbaccccaax")); // x
}
static class CharCount {
char ch;
int count;
public CharCount(char ch, int count) {
this.ch = ch;
this.count = count;
}
}
public String candyCrush(String s) {
if (s == null || s.isEmpty()) return "";
Deque<CharCount> deq = new ArrayDeque<>();
deq.addLast(new CharCount(s.charAt(0), 1));
int n = s.length();
for (int i = 1; i < n; i++) {
char ch = s.charAt(i);
if (ch != s.charAt(i - 1)) {
if (!deq.isEmpty() && deq.peekLast().count >= 3) deq.removeLast();
if (!deq.isEmpty() && deq.peekLast().ch == ch) deq.peekLast().count++;
else deq.addLast(new CharCount(ch, 1));
} else if (!deq.isEmpty()) {
deq.peekLast().count++;
}
}
if (!deq.isEmpty() && deq.peekLast().count >= 3) deq.removeLast();
StringBuilder sb = new StringBuilder();
for (CharCount cc : deq) {
sb.append(("" + cc.ch).repeat(cc.count));
}
return sb.toString();
}
}