-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompress.java
More file actions
26 lines (24 loc) · 777 Bytes
/
compress.java
File metadata and controls
26 lines (24 loc) · 777 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
import java.util.*;
public class compress{
public static void main(String args[]){
char chars[]={'a','a','b','b','c','c','c'};
int result=compress_string(chars);
System.out.println(Arrays.toString(chars));
}
public static int compress_string(char[] chars) {
int indexAns = 0, index = 0;
while(index < chars.length){
char currentChar = chars[index];
int count = 0;
while(index < chars.length && chars[index] == currentChar){
index++;
count++;
}
chars[indexAns++] = currentChar;
if(count != 1)
for(char c : Integer.toString(count).toCharArray())
chars[indexAns++] = c;
}
return indexAns;
}
}