-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringCompressor.java
More file actions
43 lines (30 loc) · 1.02 KB
/
Copy pathStringCompressor.java
File metadata and controls
43 lines (30 loc) · 1.02 KB
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
package LeetcodePractice;
public class StringCompressor {
public static int compress(char[] chars) {
int index = 0;
int i = 0;
while (i < chars.length) {
char currentChar = chars[i];
int count = 0;
while (i < chars.length && chars[i] == currentChar) {
i++;
count++;
}
chars[index++] = currentChar;
if (count > 1) {
for (char c : Integer.toString(count).toCharArray()) {
chars[index++] = c;
}
}
}
return index;
}
public static void main(String[] args) {
char[] chars1 = {'a','a','b','b','c','c','c'};
System.out.println(compress(chars1));
char[] chars2 = {'a'};
System.out.println(compress(chars2));
char[] chars3 = {'a','b','b','b','b','b','b','b','b','b','b','b','b'};
System.out.println(compress(chars3));
}
}