1+ package com .thealgorithms .strings ;
2+ /* References : https://en.wikipedia.org/wiki/Run-length_encoding
3+ * String compression algorithm deals with encoding the string, that is, shortening the size of the string
4+ * @author Swarga-codes (https://github.com/Swarga-codes)
5+ */
6+ public class StringCompression {
7+ /**
8+ * Returns the compressed or encoded string
9+ *
10+ * @param ch character array that contains the group of characters to be encoded
11+ * @return the compressed character array as string
12+ */
13+ public static String compress (String input ) {
14+ // Keeping the count as 1 since every element present will have atleast a count
15+ // of 1
16+ int count = 1 ;
17+ String compressedString = "" ;
18+ // Base condition to check whether the array is of size 1, if it is then we
19+ // return the array
20+ if (input .length () == 1 ) {
21+ return "" + input .charAt (0 );
22+ }
23+ // If the array has a length greater than 1 we move into this loop
24+ for (int i = 0 ; i < input .length () - 1 ; i ++) {
25+ // here we check for similarity of the adjacent elements and change the count
26+ // accordingly
27+ if (input .charAt (i ) == input .charAt (i + 1 )) {
28+ count = count + 1 ;
29+ }
30+ if ((i + 1 ) == input .length () - 1 && input .charAt (i + 1 ) == input .charAt (i )) {
31+ compressedString = appendCount (compressedString , count , input .charAt (i ));
32+ break ;
33+ } else if (input .charAt (i ) != input .charAt (i +1 )) {
34+ if ((i + 1 ) == input .length () - 1 ) {
35+ compressedString = appendCount (compressedString , count , input .charAt (i )) + input .charAt (i +1 );
36+ break ;
37+ } else {
38+ compressedString = appendCount (compressedString , count , input .charAt (i ));
39+ count = 1 ;
40+ }
41+ }
42+ }
43+ return compressedString ;
44+ }
45+ /**
46+ * @param res the resulting string
47+ * @param count current count
48+ * @param ch the character at a particular index
49+ * @return the res string appended with the count
50+ */
51+ public static String appendCount (String res , int count , char ch ) {
52+ if (count > 1 ) {
53+ res += ch + "" + count ;
54+ count = 1 ;
55+ } else {
56+ res += ch + "" ;
57+ }
58+ return res ;
59+ }
60+ }
0 commit comments