Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 30b6ed9

Browse files
solves string compression
1 parent be7537c commit 30b6ed9

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/StringCompression.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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+
}

0 commit comments

Comments
 (0)