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