Home > Mobile >  Compress Given String replacing the re-occurring characters with number of times they are occuring
Compress Given String replacing the re-occurring characters with number of times they are occuring

Time:11-18

public class Test12CompressString {
    public static String getCompressedString(String str) {
        String newString = "";
        int count = 1;
        int len = str.length()-1;
        for (int i = 0; i <= len ; i  ) {
            if(i != len) {
                System.out.println(i);
                if(str.charAt(i) == str.charAt(i 1)) {
                    count  ;
                    continue;
                } 
                if(count == 1) {
                    newString = newString str.charAt(i);
                } else {
                    newString = newString str.charAt(i) count;
                }
                if ( str.charAt(i) != str.charAt(i 1)) {
                    count = 1;
                    continue;
                }
            } 
        }
        return newString;
    }

    public static void main(String[] args) {
        String str = "abbbccccc";
        String ans = getCompressedString(str);
        System.out.print(ans);
    }

}

Expected Output : ab3c4

Output I am getting : ab3

Can someone tell what am I missing and why the last character and it's count is missing from my output? Can someone correct my code?

CodePudding user response:

When the for loop ends your code just returns newString. The only place where your code adds a '4' is when the loop hits a new character and recognizes that this is no longer a c. At the very end, before return newString, you should check if count exceeds 1, and if so, print count.

CodePudding user response:

As indicated in the commentary above, when your loop finishes the string, the result for the last symbol is simply thrown away.

I offer approximately the same approach as you have with some improvements.

  1. What if null was passed to your method? Your code will fall with exception. It seems to me it makes sense to return null in this case.
  2. What if the argument string is empty, another words, its length is zero? This case must be considered separately.
  3. The String class in Java are immutable. Therefore, each concatenation of the strings creates a new instance of the String object. To build the result in this such case, it is better to use a StringBuilder.
  4. In your approach, you look forward when running along the string. You compare the current symbol with the following. To do this, you need carefully watch for index not exceeds the length of the string. I propose to simplify this and not look forward at all.
  5. This is not pretty and you probably have a way to do it better. But after the end of the cycle, we need to add a last symbol in the string. This is a repeating piece of code, so I put it into a separate function.
private static String getCompressedString(String str) {
    if (Objects.isNull(str)) return null;
    if (str.isEmpty()) return "";

    StringBuilder result = new StringBuilder();
    char calculated = str.charAt(0);
    int repeats = 0;

    for (char observed : str.toCharArray()) {
        if (observed == calculated) {
            repeats  ;
        } else {
            append(result, calculated, repeats);
            calculated = observed;
            repeats = 1;
        }
    }
    append(result, calculated, repeats);

    return result.toString();
}

private static void append(StringBuilder result, char calculated, int repeats) {
    result.append(calculated);
    if (repeats > 1) {
        result.append(repeats);
    }
}

I am completely sure that there is a way to make this code better and shorter. I hope it will serve as a starting point for you.

  • Related