Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Compression loop logic

My for loop for my string compression is a bit off. I have been working on this assignment the past 5 days and I can't figure out for the life of me what is wrong. Can someone help me out?

For example, I passed over the string "TTTTrrrEe" and instead of getting T4r3Ee, I'm getting T4r3EeTT. I don't know why it jumps back to the beginning of the string like that, but I am getting closer.We can only use charAt,equals,length, and substring from the string class.

Can someone help guide me in the right direction by helping to correct my logic? I still want to try and code this myself, seeing as how it is an assignment.

public static String compress(String s){
    int count = 0;
    String temp = s.substring(0,1);
    for(int i = 0; i < s.length(); i++){
        if(i !=s.length()-1){
            if(temp.equals(s.substring(i,i+1))){
                count++;

            }else{

                if(count < 1){
                    System.out.print(s.substring(i,i+2));
                    System.out.print(temp.substring(0,1) );
                }else{
                    System.out.print("" + temp.substring(0,1) + count);
                    i--;
                    temp = s.substring(count,count+1);
                    System.out.println(" temp is now " + temp);

                    count = 0;
                    //i--;
                }
            }
        }

    }

    System.out.println(temp);

    return temp;
}
like image 806
Bob_Danelou Avatar asked Oct 22 '22 01:10

Bob_Danelou


1 Answers

Since this is a learning exercise, I wouldn't try fixing your code, just point out a few things to work on to get it right:

  • The if (i !=s.length()-1) condition inside the loop becomes unnecessary if you change your for loop condition to i < s.length()-1
  • Comparing individual characters is easier (and faster) than comparing substrings. You get a character at position i by calling char ch1 = s.charAt(i), and compare two characters using == operator, rather than calling equals() on them.
  • When count is zero (your count < 1 condition is equivalent to count == 0) you print both the current character and the character after it, in addition to the first character of temp followed by the count. This does not look correct.
  • Rather than growing temp as you go through the loop, you set it on each iteration. This does not look correct.
  • A better way of growing temp as you go through the loop is using StringBuilder and append(), instead of using a plain String, and performing concatenations.
like image 124
Sergey Kalinichenko Avatar answered Nov 04 '22 02:11

Sergey Kalinichenko