-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring-compression.java
47 lines (46 loc) · 1.44 KB
/
string-compression.java
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
44
45
46
47
class Solution {
public int compress(char[] chars) {
if(chars.length == 1) return chars.length;
int pointer = 0;
int count = 1;
char cur_char = chars[0];
for(int i =1;i<chars.length; i++){
if(cur_char != chars[i]){
if(count == 1){
chars[pointer] = cur_char;
pointer++;
cur_char = chars[i];
count = 1;
}
else{
chars[pointer] = cur_char;
cur_char = chars[i];
pointer++;
char[] chars_count = ("" + count).toCharArray();
for(char c : chars_count){
chars[pointer] = c;
pointer++;
}
count=1;
}
}
else{
count++;
}
}
if(count == 1){
chars[pointer] = cur_char;
pointer++;
}
else{
chars[pointer] = cur_char;
pointer++;
char[] chars_count = ("" + count).toCharArray();
for(char c : chars_count){
chars[pointer] = c;
pointer++;
}
}
return pointer;
}
}