0

I am working on question 1.5 from the book Cracking The Coding interview. The problem is to take a string "aabcccccaaa" and turn it into a2b1c5a3.

If the compressed string is not smaller than the original string, then return the original string.

My code is below. I used an ArrayList because I would not know how long the compressed string would be.

My output is [a, 2, b, 1, c, 5], aabc, []. When the program gets to the end of string, it doesn't have a character to compare the last character too.

import java.util.*;
import java.io.*;

public class stringCompression {

public static void main(String[] args) {

String a = "aabcccccaaa";
String b = "aabc";
String v = "aaaa";

check(a);
System.out.println("");
check(b);
System.out.println("");
check(v);

}


public static void check(String g){

ArrayList<Character> c = new ArrayList<Character>();
int count = 1;
int i = 0;
int h = g.length();


for(int j = i + 1; j < g.length(); j++)
 {
  if(g.charAt(i) == g.charAt(j)){
     count++;

 }

 else {
     c.add(g.charAt(i));
     c.add((char)( '0' + count));
     i = j;
     count = 1;
 }

}


if(c.size() == g.length()){
System.out.print(g);
}

else{

System.out.print(c);
}
}

}
1
  • 2
    Since you just bought a book that tries to help you preparing for a coding interview, I think it does not make too much sense to ask for help when you got stuck. You do not have any time pressure on you, set it aside, start again tomorrow morning and solve it on your own. You will get better and better in spotting these mistakes after each of them. Commented Aug 19, 2015 at 20:10

4 Answers 4

1

In the last loop you're not adding the result to the array. When j = g.length() still needs to add the current char and count to the array. So you could check the next value of j before increment it:

for(int j = i + 1; j < g.length(); j++)


{
  if(g.charAt(i) == g.charAt(j)){
     count++;

 }

 else {
     c.add(g.charAt(i));
     c.add((char)( '0' + count));
     i = j;
     count = 1;
 }

 if((j + 1) = g.length()){

    c.add(g.charAt(i));
    c.add((char)( '0' + count));
 }

}
Sign up to request clarification or add additional context in comments.

Comments

1

I would use a StringBuilder rather than an ArrayList to build your compressed String. When you start compressing, the first character should already be added to the result. The count of the character will be added once you've encountered a different character. When you've reached the end of the String you should just be appending the remaining count to the result for the last letter.

public static void main(String[] args) throws Exception {
    String[] data = new String[] {
        "aabcccccaaa",
        "aabc",
        "aaaa"
    };

    for (String d : data) {
        System.out.println(compress(d));
    }
}

public static String compress(String str) {
    StringBuilder compressed = new StringBuilder();

        // Add first character to compressed result
        char currentChar = str.charAt(0);
        compressed.append(currentChar);

        // Always have a count of 1
        int count = 1;
        for (int i = 1; i < str.length(); i++) {
            char nextChar = str.charAt(i);
            if (currentChar == nextChar) {
                count++;
            } else {
                // Append the count of the current character
                compressed.append(count);

                // Set the current character and count
                currentChar = nextChar;
                count = 1;

                // Append the new current character
                compressed.append(currentChar);
            }
        }
        // Append the count of the last character
        compressed.append(count);

        // If the compressed string is not smaller than the original string, then return the original string
        return (compressed.length() < str.length() ? compressed.toString() : str);
}

Results:

a2b1c5a3
aabc
a4

Comments

0

You have two errors: one that Typo just mentioned, because your last character was not added; and another one, if the original string is shorter like "abc" with only three chars: "a1b1c1" has six chars (the task is "If the compressed string is not smaller than the original string, then return the original string.")

You have to change your if statement, ask for >= instead of ==

if(c.size() >= g.length()){
    System.out.print(g);
} else {
    System.out.print(c);
}

Comments

0

Use StringBuilder and then iterate on the input string.

private static string CompressString(string inputString)
{
    var count = 1;
    var compressedSb = new StringBuilder();

    for (var i = 0; i < inputString.Length; i++)
    {
        // Check if we are at the end
        if(i == inputString.Length - 1)
        {
            compressedSb.Append(inputString[i] + count.ToString());
            break;
        }

        if (inputString[i] == inputString[i + 1])
            count++;
        else
        {
            compressedSb.Append(inputString[i] + count.ToString());
            count = 1;
        }
    }

    var compressedString = compressedSb.ToString();

    return compressedString.Length > inputString.Length ? inputString : compressedString;
}

Comments

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.