443. String Compression

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
class Solution {
public int compress(char[] chars) {
int i = 0, j = 0;
while (j < chars.length) {
// 统计当前元素次数并记录
char c = chars[j];
chars[i++] = c;
int count = 0;
while (j < chars.length && chars[j] == c) {
j++;
count++;
}
// now: j == chars.length or chars[j] != c

if (count > 1) {
int endIndex = i;
while (count != 0) {
chars[endIndex++] = (char) ('0' + count % 10);
count /= 10;
}
// now: endIndex point to next char
reverse(chars, i, endIndex - 1);
i = endIndex;
}
}

return i;
}

private void reverse(char[] chars, int i, int j) {
while (i < j) {
swap(chars, i++, j--);
}
}

private void swap(char[] chars, int i, int j) {
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
}
}

References

443. String Compression