File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
src/main/java/com/ctci/arraysandstrings Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .ctci .arraysandstrings ;
2+
3+ /**
4+ * @author rampatra
5+ * @since 24/11/2018
6+ */
7+ public class StringCompression {
8+
9+ /**
10+ * Compresses the string {@code s} such that a string {@code aabccccaaa} becomes {@code a2b1c4a3}.
11+ * Also, if the compressed string is not shorter than the original, returns the original string.
12+ *
13+ * @param str input string containing only a-z characters, both cases
14+ * @return which ever is the shorter string
15+ */
16+ private static String compressString (String str ) {
17+ StringBuilder compressedSb = new StringBuilder ();
18+ int countConsecutive = 0 ;
19+ for (int i = 0 ; i < str .length (); i ++) {
20+ countConsecutive ++;
21+
22+ /* If next character is different than current, append this char to result. */
23+ if (i + 1 >= str .length () || str .charAt (i ) != str .charAt (i + 1 )) {
24+ compressedSb .append (str .charAt (i ));
25+ compressedSb .append (countConsecutive );
26+ countConsecutive = 0 ;
27+ }
28+ }
29+ return compressedSb .length () < str .length () ? compressedSb .toString () : str ;
30+ }
31+
32+ public static void main (String [] args ) {
33+ System .out .println ("aabccccaaa: " + compressString ("aabccccaaa" ));
34+ System .out .println ("abcd: " + compressString ("abcd" ));
35+ System .out .println ("a: " + compressString ("a" ));
36+ System .out .println ("aabcccccccccccccccccccccccccaaa: " + compressString ("aabcccccccccccccccccccccccccaaa" ));
37+ }
38+ }
You can’t perform that action at this time.
0 commit comments