File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class StringCompression {
2
+ public int compress (char [] array ) {
3
+ if (array .length == 0 ) return 0 ;
4
+
5
+ StringBuilder accumulator = new StringBuilder ();
6
+ char current = array [0 ];
7
+ int count = 1 ;
8
+ for (int index = 1 ; index < array .length ; index ++) {
9
+ if (array [index ] == current ) {
10
+ count ++;
11
+ } else {
12
+ accumulator .append (current ).append (count > 1 ? count : "" );
13
+ current = array [index ];
14
+ count = 1 ;
15
+ }
16
+ }
17
+ accumulator .append (current ).append (count > 1 ? count : "" );
18
+ copyInto (array , accumulator );
19
+ return accumulator .length ();
20
+ }
21
+
22
+ private void copyInto (char [] array , StringBuilder buffer ) {
23
+ for (int index = 0 ; index < buffer .length () ; index ++) {
24
+ array [index ] = buffer .charAt (index );
25
+ }
26
+ }
27
+ }
You can’t perform that action at this time.
0 commit comments