Skip to content

Commit 97267ec

Browse files
committed
Compress string
1 parent 16e6f32 commit 97267ec

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.ctci.arraysandstrings;
2+
3+
/**
4+
* @author rampatra
5+
* @since 24/11/2018
6+
*/
7+
public class StringCompression {
8+
9+
/**
10+
* Compresses the string {@code s} such that a string {@code aabccccaaa} becomes {@code a2b1c4a3}.
11+
* Also, if the compressed string is not shorter than the original, returns the original string.
12+
*
13+
* @param str input string containing only a-z characters, both cases
14+
* @return which ever is the shorter string
15+
*/
16+
private static String compressString(String str) {
17+
StringBuilder compressedSb = new StringBuilder();
18+
int countConsecutive = 0;
19+
for (int i = 0; i < str.length(); i++) {
20+
countConsecutive++;
21+
22+
/* If next character is different than current, append this char to result. */
23+
if (i + 1 >= str.length() || str.charAt(i) != str.charAt(i + 1)) {
24+
compressedSb.append(str.charAt(i));
25+
compressedSb.append(countConsecutive);
26+
countConsecutive = 0;
27+
}
28+
}
29+
return compressedSb.length() < str.length() ? compressedSb.toString() : str;
30+
}
31+
32+
public static void main(String[] args) {
33+
System.out.println("aabccccaaa: " + compressString("aabccccaaa"));
34+
System.out.println("abcd: " + compressString("abcd"));
35+
System.out.println("a: " + compressString("a"));
36+
System.out.println("aabcccccccccccccccccccccccccaaa: " + compressString("aabcccccccccccccccccccccccccaaa"));
37+
}
38+
}

0 commit comments

Comments
 (0)