We are given a string which is compressed and we have to decompress it.
(a(bc2)d2)$
"$" indicates end of string.
(abcbcd2)$
abcbcdabcbcd (This is the final uncompressed string.)
My code:
import java.util.*;
class decompress
{
public static void main(String[] ar)
{
int end = 0, st = 0;
Scanner sc = new Scanner(System.in);
System.out.print(">> ");
String s = sc.next();
while(s.indexOf('(') != -1)
{
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if(c == '(')
st = i;
else if(c == ')')
{
end = i;
String t = s.substring(st+1,end);
int n = t.charAt(t.length()-1) - '0';
t = t.substring(0,t.length() - 1);
String q = "";
for(int j = 0; j < n; j++)
q += t;
String m = "";
if(st != 0)
m = s.substring(0,st);
s = m + q + s.substring(i+1);
break;
}
}
}
System.out.println(s);
}
}
Is there a more elegant way to make this program ?