1 package chapter1;
2 /*
3 * Q:given a string ,compression the string by duplicate char
4 * if compressed string not short than orignal,then return orignal string
5 * E:input:"aabcccc"
6 output:"a2b1c4"
7 * S:Count the Consecutive char,and append it when different
8 */
9 public class Q6 {
10 public static String compression(String s) {
11 StringBuilder compressed=new StringBuilder();
12 int CountConsecutive=0;
13 for(int i=0;i<s.length();i++) {
14 CountConsecutive++;
15 if(i+1>=s.length()||s.charAt(i)!=s.charAt(i+1)) {
16 compressed.append(s.charAt(i));
17 compressed.append(CountConsecutive);
18 CountConsecutive=0;
19 }
20 }
21 return compressed.length()<s.length()?compressed.toString():s;
22 }
23
24 public static void main(String[] args) {
25 String str="aabcccc";
26 System.out.println(compression(str));
27 }
28
29 }