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