I wrote an answer for the following question and wondering if there is any better approach to it.
Using the Java language, have the function
RunLength(str)
take thestr
parameter being passed and return a compressed version of the string using the Run-length encoding algorithm. This algorithm works by taking the occurrence of each repeating character and outputting that number along with a single character of the repeating sequence.For example: "wwwggopp" would return 3w2g1o2p. The string will not contain any numbers, punctuation, or symbols.
Code
public class App {
void runLength(String str) {
HashMap<Character, Integer> hash = new HashMap<Character, Integer>();
Character c;
for (int i = 0; i < str.length(); i++) {
c = str.toLowerCase().charAt(i);
if (hash.containsKey(c)) {
int value = hash.get(c);
value++;
hash.put(c, value);
} else {
hash.put(c, 1);
}
}
int value = 0;
StringBuffer buf = new StringBuffer();
String temp;
for (int j = 0; j < str.length(); j++) {
c = str.toLowerCase().charAt(j);
value = hash.get(c);
temp = str.substring(j, j + 1);
if (buf.indexOf(c.toString()) == -1) {
buf.append(value);
buf.append(temp);
}
}
System.err.println(buf.toString());
}
public static void main(String[] args) {
new App().runLength("wwwggopp");
}
}
Output
3w2g1o2p
wwwgggooopppwww
? It appears that your code will not be able to handle this case. \$\endgroup\$