-
Notifications
You must be signed in to change notification settings - Fork 2
/
StringCompression.java
56 lines (48 loc) · 1.58 KB
/
StringCompression.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
class Solution {
public int compress(char[] chars) {
if (chars == null || chars.length == 0) {
return 0;
}
if (chars.length == 1) {
return 1;
}
int result = 0;
int slow = 0;
int fast = 1;
while (fast < chars.length) {
if (chars[fast] == chars[slow]) {
fast ++;
} else {
if (fast == slow + 1) {
chars[result] = chars[slow];
result++;
} else {
int distance = fast - slow;
String distanceString = Integer.toString(distance);
chars[result] = chars[slow];
result ++;
for (int i = 0; i < distanceString.length(); i++) {
chars[result] = distanceString.charAt(i);
result++;
}
}
slow = fast;
fast ++;
}
}
if (slow + 1 == fast) {
chars[result] = chars[slow];
result++;
} else {
int distance = fast - slow;
String distanceString = Integer.toString(distance);
chars[result] = chars[slow];
result ++;
for (int i = 0; i < distanceString.length(); i++) {
chars[result] = distanceString.charAt(i);
result++;
}
}
return result;
}
}