Skip to content

Commit 821ec33

Browse files
committed
add StringCompressionTest
1 parent 957d03b commit 821ec33

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package com.ctci.arraysandstrings;
2+
3+
import org.junit.jupiter.api.AfterEach;
4+
import org.junit.jupiter.api.BeforeEach;
5+
import org.junit.jupiter.api.Test;
6+
7+
import static org.junit.jupiter.api.Assertions.*;
8+
9+
class StringCompressionTest {
10+
@Test
11+
void case1() {
12+
String input = "";
13+
String expectedOutput = "";
14+
String actualOutput = compressString(input);
15+
assertEquals(expectedOutput, actualOutput);
16+
}
17+
18+
@Test
19+
void case2() {
20+
String input = "abc";
21+
String expectedOutput = "abc";
22+
String actualOutput = compressString(input);
23+
assertEquals(expectedOutput, actualOutput);
24+
}
25+
26+
@Test
27+
void case3() {
28+
String input = "aaabbccc";
29+
String expectedOutput = "a3b2c3";
30+
String actualOutput = compressString(input);
31+
assertEquals(expectedOutput, actualOutput);
32+
}
33+
34+
@Test
35+
void case4() {
36+
String input = "aaabbbccc";
37+
String expectedOutput = "a3b3c3";
38+
String actualOutput = compressString(input);
39+
assertEquals(expectedOutput, actualOutput);
40+
}
41+
42+
@Test
43+
void case5() {
44+
String input = "abcd";
45+
String expectedOutput = "abcd";
46+
String actualOutput = compressString(input);
47+
assertEquals(expectedOutput, actualOutput);
48+
}
49+
50+
51+
private static String compressString(String str) {
52+
StringBuilder compressedSb = new StringBuilder();
53+
int countConsecutive = 0;
54+
for (int i = 0; i < str.length(); i++) {
55+
countConsecutive++;
56+
57+
/* If next character is different than current, append this char to result. */
58+
if (i + 1 >= str.length() || str.charAt(i) != str.charAt(i + 1)) {
59+
compressedSb.append(str.charAt(i));
60+
compressedSb.append(countConsecutive);
61+
countConsecutive = 0;
62+
}
63+
}
64+
return compressedSb.length() < str.length() ? compressedSb.toString() : str;
65+
}
66+
}

0 commit comments

Comments
 (0)