File tree Expand file tree Collapse file tree
src/main/java/com/fishercoder/solutions/firstthousand Expand file tree Collapse file tree Original file line number Diff line number Diff line change 22
33public 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}
You can’t perform that action at this time.
0 commit comments