Avoid printing in methods, unless the purpose of the method is speicifically to print. The main purpose of the runLength method is certainly not to print. It should return the compressed value instead.
The description doesn't say that you should treat upper and lowercase characters equal. It's not correct to do that. And if you really wanted to do that,
it would have been simpler to lowercase the entire input string once.
This is a very wasteful operation:
for (int i = 0; i < str.length(); i++) {
c = str.toLowerCase().charAt(i);
This would have been much better:
String lowered = str.toLowerCase();
for (int i = 0; i < lowered.length(); i++) {
c = lowered.charAt(i);
Declare variables with the interface type, when possible.
Instead of:
HashMap<Character, Integer> hash = new HashMap<Character, Integer>();
This would have been better:
Map<Character, Integer> hash = new HashMap<Character, Integer>();
Btw are you still on Java6? You should definitely migrate to at least Java7,
where the above declaration becomes simply:
Map<Character, Integer> hash = new HashMap<>();
Suggested implementation
This is simpler, without a hashmap:
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(count).append(prev);
count = 1;
}
prev = current;
}
return builder.append(count).append(prev).toString();
}
Unit testing
It's always good to have unit tests to verify correctness:
@Test
public void test_aabcccccaaa() {
assertEquals("2a1b5c3a", compress("aabcccccaaa"));
}
@Test
public void test_a5() {
assertEquals("5a", compress("aaaaa"));
}
@Test
public void test_empty() {
assertEquals("", compress(""));
}
@Test
public void test_a() {
assertEquals("1a", compress("a"));
}
@Test
public void test_a3b4() {
assertEquals("3a4b", compress("aaabbbb"));
}
@Test
public void test_abc() {
assertEquals("1a1b1c", compress("abc"));
}
@Test
public void test_wwwggopp() {
assertEquals("3w2g1o2p", compress("wwwggopp"));
}