Skip to content

Commit 8e6ef37

Browse files
update 443
1 parent 8baa909 commit 8e6ef37

1 file changed

Lines changed: 23 additions & 29 deletions

File tree

  • src/main/java/com/fishercoder/solutions/firstthousand

src/main/java/com/fishercoder/solutions/firstthousand/_443.java

Lines changed: 23 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2,39 +2,33 @@
22

33
public class _443 {
44
public static class Solution1 {
5-
/*
6-
* This is breaking the rules, it's not in-place.
7-
*/
85
public int compress(char[] chars) {
9-
if (chars == null || chars.length == 0) {
10-
return 0;
11-
}
12-
StringBuilder sb = new StringBuilder();
13-
int count = 1;
14-
char prev = chars[0];
15-
for (int i = 1; i < chars.length; i++) {
16-
if (chars[i] == prev) {
17-
count++;
18-
} else {
19-
if (count > 1) {
20-
sb.append(prev);
21-
sb.append(count);
22-
} else if (count == 1) {
23-
sb.append(prev);
6+
int i = 0; // Read pointer
7+
int res = 0; // Write pointer
8+
9+
while (i < chars.length) {
10+
int j = i;
11+
// Advance j to find the end of the repeating group
12+
while (j < chars.length && chars[j] == chars[i]) {
13+
j++;
14+
}
15+
16+
// 1. Write the character
17+
chars[res++] = chars[i];
18+
19+
// 2. If the group length is greater than 1, write the count
20+
int groupLength = j - i;
21+
if (groupLength > 1) {
22+
for (char c : Integer.toString(groupLength).toCharArray()) {
23+
chars[res++] = c;
2424
}
25-
prev = chars[i];
26-
count = 1;
2725
}
26+
27+
// 3. Move the read pointer to the start of the next group
28+
i = j;
2829
}
29-
sb.append(prev);
30-
if (count > 1) {
31-
sb.append(count);
32-
}
33-
int i = 0;
34-
for (char c : sb.toString().toCharArray()) {
35-
chars[i++] = c;
36-
}
37-
return sb.length();
30+
31+
return res;
3832
}
3933
}
4034
}

0 commit comments

Comments
 (0)