-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode_443.java
More file actions
32 lines (30 loc) · 946 Bytes
/
Copy pathleetcode_443.java
File metadata and controls
32 lines (30 loc) · 946 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
31
32
public class leetcode_443 {
public static int compress(char[] chars){
int n=chars.length;int i=0;//read pointer
int index=0;//write pointer
while(i<n){
char cur=chars[i];
int count=0;
while(i<n&&chars[i]==cur){
i++;count++;
}
chars[index++]=cur;
if(count>1){
String countstr=Integer.toString(count);
for(char ch:countstr.toCharArray()){
chars[index++]=ch;
}
}
}
return index;
}
public static void main(String[] args){
char[] chars={'a', 'a', 'b', 'b', 'c', 'c', 'c'};
int newlength=compress(chars);
System.out.println("Compressed Array Length"+newlength);
System.out.print("Compressed Array");
for (int i = 0; i < newlength; i++) {
System.out.print(chars[i] + " ");
}
}
}