1+ package com .rampatra .strings ;
2+
3+ /**
4+ * @author rampatra
5+ * @since 2019-04-08
6+ */
7+ public class CompressString {
8+
9+ /**
10+ * Compress a string, consisting of only alphabets, such that the compressed string contains the letter and
11+ * a number next to it representing the number of times it is repeated. Also, compress only if the letter is
12+ * repeated more than once and ignore it occurs just once.
13+ * EXAMPLE:
14+ * Input: aaabbcdd
15+ * Output: a3b2cd2
16+ * <p>
17+ * Time Complexity: O(n)
18+ * Space Complexity: O(n)
19+ * where,
20+ * n is the number of characters in the input string
21+ *
22+ * @param str the input string consisting on only alphabets
23+ * @return the compressed string
24+ */
25+ private static String compress (String str ) {
26+ // some basic validation
27+ if (str .length () == 0 ) {
28+ throw new IllegalArgumentException ("Empty String" );
29+ }
30+
31+ StringBuilder sb = new StringBuilder ();
32+ int letterCount = 0 ;
33+
34+ for (int i = 0 ; i < str .length (); i ++) {
35+ /*
36+ When the current character is a different one, append the previous character and its count to the
37+ result, and finally, reset the counter
38+ */
39+ if (i != 0 && str .charAt (i ) != str .charAt (i - 1 )) {
40+ sb .append (str .charAt (i - 1 ));
41+ if (letterCount > 1 ) sb .append (letterCount );
42+ letterCount = 0 ;
43+ }
44+ letterCount ++;
45+ }
46+
47+ // last character
48+ sb .append (str .charAt (str .length () - 1 ));
49+ if (letterCount > 1 ) sb .append (letterCount );
50+
51+ return sb .toString ();
52+ }
53+
54+ public static void main (String [] args ) {
55+ System .out .println (compress ("a" ));
56+ System .out .println (compress ("aabbcc" ));
57+ System .out .println (compress ("aabcc" ));
58+ System .out .println (compress ("aaaabbbccaad" ));
59+ }
60+ }
0 commit comments