Compress the String

 

Write a program to do basic string compression. For a character which is consecutively repeated more than once, replace consecutive duplicate occurrences with the count of repetitions.

Sample Input 1:
aaabbccdsa
Sample Output 1:
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

Popular posts from this blog

Minimum Length Word

Check Number Sequence