Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Can anyone solve this! man this is very hard to me all PRO-grammers its a challenge!!!!

Craig Dennis please help me sir... Write a program to do basic string compression. For a character which is repeated more than once, replace consecutive duplicate occurrences with the count of repetitions e.g. if a String has 'x' repeated 5 times, replace this "xxxxx" with "x5".

1 Answer

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

I'll give you some pseudo code....

Create a new string var
Create a previous character var
Create counter var
Loop through each character in original string
     Is current char equal to previous?
           Increment counter
     Otherwise
            Write letter
             Is counter greater than one?
                   Write counter
                   Reset counter

Craig Dennis sir can you please tell what is wrong in my logic that i build in more than 6hr i'm really feeling very bad about me :(

class Solution {
    public static String compress(String inputString) {
        char arr[] = inputString.toCharArray();
        int i = 0, j = 0, sign = 0;
        String returningString = "";   
        while(i<arr.length) {  
            sign = 1;
            j = i;
            while(arr[j] == arr[j+1]) {
                sign++;
                j++;
            }
            if(sign != 1) {
                returningString += returningString.concat(Integer.toString(sign));
                returningString += returningString.concat(Character.toString(arr[i]));
            }
            if(sign == 1) {
                returningString += returningString.concat(Character.toString(arr[i]));
            }
            i += sign;
        }
        returningString += returningString.concat(Character.toString(arr[i]));
        return returningString;
    }
    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.compress("aaabbccds"));
    }
}```