Monday, December 8, 2014

Implementing Basic String Compression using the counts of repeated characters [Coding Question][Java]

Q: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not becomes smaller than the original string, your method should return the original string.

Source:

public class Code {
    
    public static boolean isBeneficial(String source){
        int count=0;
        for(int i= 0;i<source.length();++i){
            count+=2;
            while(i+1<source.length() && source.charAt(i)==source.charAt(i+1)) i++;
        } 
        return count<source.length();
    }
    
    public static String compress(String source){
        if(!isBeneficial(source))return source;
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<source.length();++i){
            int count = 1;
            while(i+1<source.length() && source.charAt(i )== source.charAt(i+1)){
                i++; 
                count++;
            }  
            sb.append(source.charAt(i)).append(count); 
        }  
        return sb.toString();
    }
    
    public static void main(String[] args){ 
        System.out.println(compress("abxxxxxxccccc")); 
        System.out.println(compress("abccc")); 
    }
}

Output:

a1b1x6c5

abccc

No comments:

Post a Comment