import java.util.*; public class Compression { public static void main(String[] args){ String input = "abcdabcdabcdefefefefgggggg\n"+ "aabbaabbbbaabb\n"+ "bananananas fors fors\n" + "aaaaa a a aaaaaa\n" + "aaaaa a a aaaa"; Scanner s = new Scanner( input); while(s.hasNextLine()){ String line = s.nextLine(); String cline = process(line); System.out.println(line +"===>>>" + cline); } } public static String process(String line){ //System.out.println("line:" + line); if(line.length() == 0 || line.length() == 1){ return line; } String largest = ""; int saving = 0; // the amount of saving in the compression PP p = new PP(0,0); // the from,to indexes of substring int count =1; // how many a substring is repeated for(int i=0;i saving || (newSaving==saving && newLen >= (p.to-p.from)*count) || saving ==0){ largest = line.substring(i,j); saving = (newCount -1)* (j-i); p.set(i,j); count = newCount; } } } //System.out.println("largest:" + largest +"-->>" + compress(largest,count)); String preLine = ""; String postLine = ""; if( p.from > 0){ preLine = line.substring(0,p.from); } int ri = p.from + (p.to - p.from) * count; if( ri < line.length()){ postLine = line.substring(ri); } return process( preLine)+ compress(largest,count) + process( postLine); } public static String compress(String str, int c){ if(c == 1) return str; return (c < 10 ? ("0" + c) : (c+"") ) + (str.length() < 10? "0" + str.length() : str.length()) + str; } public static int countRepeated(String line, int from ,int to){ String sub = line.substring(from,to); int len = to - from; int c = 1; while(true){ from = to; to += len; if(to > line.length()) break; String sub2 = line.substring(from,to); if(sub.equals(sub2)) c++; else break; } return c; } } class PP{ int from; int to; public PP(int from , int to){ this.from = from; this.to = to; } public void set(int from, int to){ this.from = from; this.to = to; } }