1

I am looking to implement a method to perform basic string compression in the form of:

aabcccccaaa -> a2b1c5a3

I have this program:

import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    String str = sc.nextLine();

    System.out.println(compress(str));
  }

  public static String compress(String str) {
    char[] chars = str.toCharArray();

    int count = 0;
    String result = "";

    for (int i = 0; i < chars.length; i++) {
      char curr = chars[i];
      result += curr;

      for (int j = i; j < chars.length; j++) {
        if (chars[j] == curr) {
          count++;
        }
        else {
          i += count;
          break;
        }
      }
      result += count;
      count = 0;
    }

    return result;
  }

}

But in my tests I am always missing the last character count.

I assume this is because the program gets out of the inner for loop before it should, but why is this the case?

Thanks a lot

5
  • 1
    yeah you need to keep track of the last character you end up coming across and when you exit your for loop add the a3 to your string Commented Dec 7, 2016 at 22:50
  • 1
    Running it with aaabbbccc gives a3b2c2c1. You need to rethink about your algorithm. In particular, about the way you increment i.
    – JB Nizet
    Commented Dec 7, 2016 at 22:50
  • 1
    Do not build potentially long Strings "adding" to the current, immutable value of a variable of type String: use StringBuilder.append(). Try to use just one iteration.
    – greybeard
    Commented Dec 7, 2016 at 22:50
  • 1
    A great way to figure this kind of thing out is to use a debugger
    – Simon
    Commented Dec 7, 2016 at 22:52
  • 3
    Sounds like an "off by one error". You should use a debugger to help you track down the exact problem. Debugging skills are very important for any programmer. In fact, they are more important than knowing how to write code. Commented Dec 7, 2016 at 23:03

3 Answers 3

1

You don't need two for loops for this and can do it in one go like so

    String str = "aaabbbbccccca";
    char[] chars = str.toCharArray();
    char currentChar = str.length() > 0 ? chars[0] : ' ';
    char prevChar = ' ';
    int count = 1;
    StringBuilder finalString = new StringBuilder();

    if(str.length() > 0)
    for(int i = 1; i < chars.length; i++)
    {
        if(currentChar == chars[i])
        {
            count++;
        }else{
            finalString.append(currentChar + "" + count);
            prevChar = currentChar;
            currentChar = chars[i];
            count = 1;
        }
    }

    if(str.length() > 0 && prevChar != currentChar)
        finalString.append(currentChar + "" + count);

    System.out.println(finalString.toString());

Output is: a3b4c5a1 for aaabbbbccccca

1
  • The code looks carelessly formatted. Why don't you just let your IDE format the code for you? Commented Jun 13, 2020 at 6:31
-1
Keep a track of character that you are reading and compare it with next character of the string. If it is different, reset the count.

public static void stringCompression (String compression) {
        String finalCompressedString = "";
        char current = '1';
        int count = 0;

        compression = compression + '1';

        for (int i = 0; i < compression.length(); i++) {
            if (compression.charAt(i) == current) {
                count = count + 1;
            } else {
                if (current != '1') 
                    finalCompressedString = finalCompressedString + (current + Integer.toString(count));
                    count = 1;
                    current = compression.charAt(i);
            }
        }
        System.out.println(finalCompressedString);
    }
1
  • (Do not build potentially long Strings "adding" to a current, immutable value of type String: use StringBuilder.append().) Does this work for "press1"?
    – greybeard
    Commented Aug 6, 2017 at 5:55
-1

My answer for String Compression in java. In this what i have done is and what you should have done is that , Keep a record of the characters that that are coming for a specific number of times, do so by comparing the current character with the next character , and when the current and the next character become unequal reset the value of count and repeat the whole process again for the next different character. Hope it helps!

import java.util.*;
public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int count = 0;
        for (int i=0; i<str.length(); ++i) {
            int j=i+1;
            count=1;
            while (j!=str.length() && str.charAt(i) == str.charAt(j)) {
                count += 1;
                j += 1;
                i += 1;
            }
            System.out.print(str.charAt(i));
            if (count > 1) {
                System.out.print(count);
            }
        }
    }
}
1
  • Thanks for improving your answer. I still don't like it though since your code is worse than the original code. The method name main does not appropriately describe what it is doing, and the count should be appended unconditionally. Commented Jun 13, 2020 at 6:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.