1+ package com .rampatra .strings ;
2+
3+ /**
4+ * @author rampatra
5+ * @since 30/11/2018
6+ */
7+ public class KeepOnlyKConsecutiveLetters {
8+
9+ /**
10+ * A method which takes a string {@code str} and a number {@code k} and
11+ * returns a string with at most {@code k} consecutive characters in the
12+ * string.
13+ * <p>
14+ * For example,
15+ * 1) aaaaaabbbbbccccc, 3 -> aaabbbccc
16+ * 2) abc, 2 -> abc
17+ * 3) aabbccc, 3 -> aabbccc
18+ *
19+ * @param str input string
20+ * @param k
21+ * @return
22+ */
23+ private static String keepOnlyKConsecutiveLetters (String str , int k ) {
24+ StringBuilder sb = new StringBuilder ();
25+
26+ for (int i = 0 ; i < str .length (); i ++) {
27+ char ch = str .charAt (i );
28+
29+ for (int j = 0 ; i + j < str .length () && j < k ; j ++) {
30+ char ch2 = str .charAt (i + j );
31+ if (ch2 == ch ) {
32+ sb .append (ch2 );
33+ } else {
34+ break ;
35+ }
36+ }
37+
38+ while (i + 1 < str .length () && str .charAt (i + 1 ) == str .charAt (i )) {
39+ i ++;
40+ }
41+ }
42+ return sb .toString ();
43+ }
44+
45+ public static void main (String [] args ) {
46+ System .out .println ("aaaaabbbbbccccc, 5: " + keepOnlyKConsecutiveLetters ("aaaaabbbbbccccc" , 5 ));
47+ System .out .println ("aaaaabbbbbccccc, 2: " + keepOnlyKConsecutiveLetters ("aaaaabbbbbccccc" , 2 ));
48+ System .out .println ("aaaaabbbbbccccc, 1: " + keepOnlyKConsecutiveLetters ("aaaaabbbbbccccc" , 1 ));
49+ System .out .println ("aabbcc, 2: " + keepOnlyKConsecutiveLetters ("aabbcc" , 2 ));
50+ System .out .println ("aabbcc, 0: " + keepOnlyKConsecutiveLetters ("aabbcc" , 0 ));
51+ System .out .println ("abc, 2: " + keepOnlyKConsecutiveLetters ("abc" , 2 ));
52+ }
53+ }
0 commit comments