0
    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!

Attachments Screenshot_(656).png 78.56 KB
3
Contributors
3
Replies
18
Views
4 Months
Discussion Span
Last Post by JamesCherrill
0

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.

Edited by JamesCherrill

0

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;
    }
0

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?

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.