-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompress.java
More file actions
30 lines (28 loc) · 848 Bytes
/
compress.java
File metadata and controls
30 lines (28 loc) · 848 Bytes
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
public class compress {
public static void main(String[] args) {
char[] chars = { 'a', 'a', 'b', 'b', 'b', 'c', 'c' };
chars = compresser(chars);
for (char c : chars) {
System.out.print(c + " ");
}
}
public static char[] compresser(char[] chars) {
int i = 0; // less than chars.length
int index = 0; // length of new array
while (i < chars.length) {
char c = chars[i];
int count = 0;
while (i < chars.length && chars[i] == c) {
i++;
count++;
}
chars[index++] = c;
if (count != 1) {
for (char s : String.valueOf(count).toCharArray()) {
chars[index++] = s;
}
}
}
return chars;
}
}