public class roughLargestSmallest {
public static void main(String[] args) {
    System.out.println(" Enter a sentence ");
    String x = IO.readString();
    compress(x);

}
public static String compress(String original) {
    int count = 1;
    StringBuilder builder = new StringBuilder();

    for (int i = 1; i < original.length() - 1; i++) {
        if (original.charAt(i) == original.charAt(i - 1)) {
            count++;
        } else {
            builder.append(original.charAt(i - 1));
            builder.append(count);
            count = 1;
        }
    }

    if (original.length() > 1) {
        if (original.charAt(original.length() - 1) == original.charAt(original.length() - 2)) {
            count++;
        } else {
            builder.append(original.charAt(original.length() - 2));
            builder.append(count);
            count = 1;
        }
        builder.append(original.charAt(original.length() - 1));
        builder.append(count);
    }
    System.out.println(builder);
    return builder.toString();
}
}

Attached is my code, it passes some of the test cases, but not the most. can anyone help me figure what i'm doing wrong? thanks!

Recommended Answers

All 3 Replies

Lines 22-32 are not needed if you fix the termination condition for the loop on line 12

The spec says you do not include the count if it is 1, but your code always includes it.

I did this

public static String Compress(String str) {
        String comp;
        char[] chars = str.toCharArray();
        char[] charFinal = new char[chars.length];
        int index = 0;
        for(int i=0; i<chars.length; i++) {
            Integer count = 0;
            for(int j=i+1; j<chars.length; j++) {
                if(chars[i] == chars[j]) {
                    count++;
                }
                else if(chars[i] != chars[j]) {
                    count++;
                    i = j-1;
                    break;
                }
            }
            charFinal[index] = chars[i];
            charFinal[++index] = count.toString().charAt(0);
            if(chars[chars.length - 1] == charFinal[index - 1]) break;
            index++;

        }
        comp = String.copyValueOf(charFinal);

        return comp;
    }

Kishan:

Is that supposed to be a solution to ahmedrizwan's problem? Did you test it? It's certainly hard to follow... eg changing an outer loop's control variable from an inner loop, redundant if on line 12, using an Integer as opposed to an int...
What was your intention in posting it?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.