As @vnp said, don't print the result for "testing". Convert each statement in the main method to proper unit tests, for example:
@Test
public void test_aabcccccaaa() {
assertEquals("a2b1c5a3", compress("aabcccccaaa"));
}
@Test
public void test_a5() {
assertEquals("a5", compress("aaaaa"));
}
Once this is done, you can go ahead and safely refactor the rest of the code, having an easy way to repeat the tests.
Being aware of, and working knowledge of unit testing should definitely score you extra points in a job interview, or might be even required.
Bug
For single letter inputs, the method seems to return an empty string. That looks incorrect. Judging by that for "abc" it returns "a1b1c1", it would seem that for "a" it should return "a1" instead of an empty string
Simplify
The algorithm can be simplified to these steps:
- Loop over the characters, from the 2nd till the end
- If the current character is the same as the previous, increment the count
- If different, append the count and append the previous character
- After the end of the loop, append the count
The implementation can be something like this:
public String compress(String str) {
if (str.isEmpty()) {
return "";
}
char[] chars = str.toCharArray();
StringBuilder builder = new StringBuilder();
int count = 1;
char prev = chars[0];
for (int i = 1; i < chars.length; i++) {
char current = chars[i];
if (current == prev) {
count++;
} else {
builder.append(prev).append(count);
count = 1;
}
prev = current;
}
return builder.append(prev).append(count).toString();
}
Order of expressions in if statement
Your code would be more readable if you would be consistent with your ordering in the if clause. You have
str.charAt(i) == str.charAt(i - 1) && i < str.length() - 1
but:
i == str.length() - 1 && str.charAt(i) == str.charAt(i - 1)
instead of:
str.charAt(i) == str.charAt(i - 1) && i == str.length() - 1
Last Loop
You have two conditions that only apply in the last loop. I would pull those out to after the loop:
public static String compress(String str) {
int count = 1;
StringBuilder builder = new StringBuilder();
for (int i = 1; i < str.length() - 1; i++) {
if (str.charAt(i) == str.charAt(i - 1)) {
count++;
} else {
builder.append(str.charAt(i - 1));
builder.append(count);
count = 1;
}
}
// special cases for last chars
if (str.length() > 1) {
if (str.charAt(str.length() - 1) == str.charAt(str.length() - 2)) {
count++;
} else {
builder.append(str.charAt(str.length() - 2));
builder.append(count);
count = 1;
}
builder.append(str.charAt(str.length() - 1));
builder.append(count);
}
return builder.toString();
}