forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_443.java
40 lines (39 loc) · 1.15 KB
/
_443.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
package com.fishercoder.solutions;
public class _443 {
public static class Solution1 {
/**
* This is breaking the rules, it's not in-place.
*/
public int compress(char[] chars) {
if (chars == null || chars.length == 0) {
return 0;
}
StringBuilder sb = new StringBuilder();
int count = 1;
char prev = chars[0];
for (int i = 1; i < chars.length; i++) {
if (chars[i] == prev) {
count++;
} else {
if (count > 1) {
sb.append(prev);
sb.append(count);
} else if (count == 1) {
sb.append(prev);
}
prev = chars[i];
count = 1;
}
}
sb.append(prev);
if (count > 1) {
sb.append(count);
}
int i = 0;
for (char c : sb.toString().toCharArray()) {
chars[i++] = c;
}
return sb.length();
}
}
}