I was given this small task in an interview recently. I'm usually terrible at coding questions in interviews, because with the time constraint and the lack of google I usually overthink and rush stuff and just end up with a mess of a program.
The task was to write a program that would compress the length of string, and compare the length of the compressed string to the input string and return whichever one is smaller. Example would be: input string "aaabcccc" would be compressed to "a3b1c4".
I essentially split the string into a charArray and then counted each occurrence of a character and stored them into a hashmap, and looped through the map to build the new string. Just from a learning perspective, was there a better way to do this? I was given ~10 minutes to write it as well, it more to assess how I would solve the problem as opposed to the code itself. But regardless, I'd like a review of it:
import java.util.HashMap;
import java.util.Map.Entry;
public class Compressor {
public static void main(String args []) {
String randomString = "aaabccccc";
HashMap<Character, Integer> map = countCharacters(randomString);
String compressedString = createCompressedString(map);
if(randomString.toCharArray().length < compressedString.toCharArray().length) {
System.out.println(randomString);
}
else {
System.out.println(compressedString);
}
}
/**
* Create hasmap to store character and count of occurrence
* @param s
* @return
*/
private static HashMap<Character, Integer> countCharacters(String s) {
HashMap<Character, Integer> characterCount = new HashMap<Character, Integer>();
char[] characterArray = s.toCharArray();
for(Character c : characterArray) {
int newCount;
Integer count = characterCount.get(c);
if(count == null) {
newCount = 1;
}
else {
newCount = count + 1;
}
characterCount.put(c, newCount);
}
return characterCount;
}
/**
* Convert hashmap into a string
* @param map
* @return
*/
private static String createCompressedString(HashMap<Character, Integer> map) {
String newString = "";
for (Entry<Character, Integer> entry : map.entrySet()) {
Character key = entry.getKey();
Integer value = entry.getValue();
newString += "" + key + "" + value;
}
return newString
}
}
aaaabbbbaaaa
? \$\endgroup\$a8b4
, but I can see what you're getting at. I'd be interested in knowing a way to get it to compress intoa4b4a4
in this case \$\endgroup\$a4b4a4
allows to reconstructaaaabbbbaaaa
.a8b4
is a histogram rather than a decompressible representation. Then again, from the "proposed solution" cited in Duarte Meneses's (non-)answer, the intended solution would be the RLE one. (The code cited leaves much to be desired.) \$\endgroup\$