-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestion31.java
More file actions
38 lines (32 loc) · 1.01 KB
/
question31.java
File metadata and controls
38 lines (32 loc) · 1.01 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
public class question31 {
public static void main(String[] args) {
StringCompressor sc = new StringCompressor();
char[] input = {'a','a','b','b','c','c','c'};
int len = sc.compress(input);
System.out.println("Compressed Length: " + len);
for (int i = 0; i < len; i++) {
System.out.print(input[i] + " ");
}
}
}
class StringCompressor {
public 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 : String.valueOf(count).toCharArray()) {
chars[index++] = c;
}
}
}
return index;
}
}