The task is to compress a string.
eg. "abcbcdabcbcd"
Here as you can see some characters are repeated, so it can be compressed.
"abcbcdabcbcd" -> "(a(bc2)d2)$"
'$' denotes end of string.
My code:
import java.util.*;
class compress
{
public static void main(String[] ar)
{
System.out.print(">> ");
Scanner sc = new Scanner(System.in);
String s = sc.next();
System.out.println(compress(s));
}
public static String compress(String s)
{
String a = "";
boolean found = false;
for(int l = 0; l < s.length(); l++)
{
for(int i = l; i < s.length(); i++)
{
String t = s.substring(l,i+1);
try
{
int q = 1;
int st = i+1;
String p = "";
while(st + t.length() <= s.length())
{
p = s.substring(st,st+t.length());
if(p.equals(t))
q++;
else break;
st += t.length();
}
if(q != 1)
{
a += "(" + compress(t) + q + ")";
l = st-1;
i = st;
found = true;
}
}catch(Exception e){}
}
if(!found)
a += s.charAt(l);
found = false;
}
return a;
}
}
Please help to improve my code and suggest a better solution.
void main
a paste glitch? FWIW I'm not buyingcatch(Exception e){}
. – Mat's Mug♦ Dec 19 '13 at 19:09(a(bc2)d2)$
be something like((a(bc2)d)2)$
? logically I would think that you want the patterna(bc2)d
to repeat twice, not haved
repeat twice at the end. – Malachi Dec 20 '13 at 16:36