Compress the String
aaabbccdsa
a3b2c2dsa
import java.util.Scanner;
public class CompressString {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String st = s.nextLine();
String c = getCompressedString(st);
System.out.println(c);
}
public static String getCompressedString(String str) {
String s="";
int l=str.length();
for(int i=0;i<l;i++)
{
// Count occurrences of current character
int count = 1;
while (i < l - 1 && str.charAt(i) == str.charAt(i + 1))
{
count++;
i++;
}
if (count == 1)
{
s=s+str.charAt(i);
}
else
{
s=s+str.charAt(i)+count;
}
}
return s;
}
}
Comments
Post a Comment