Stumbled upon this interview question:
Given a morse encoded sentence with no spaces or separation between letters or words and a list of words contained in the message, decode it.
This was my solution (and a test case with the jack and jill sentence):
static String[] alpha = {"a","b","c","d","e","f","g","h","i","j","k",
"l","m","n","o","p","q","r","s","t","u","v",
"w","x","y","z"};
static String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",
".--","-..-","-.--","--.."};
private static HashMap<Character, String> letters = new HashMap<>();
public static void main(String[] args) {
for (int i = 0; i < alpha.length; i++) {
letters.put(alpha[i].charAt(0), morse[i]);
}
String[] words = {"hill","jack","went","and","jill","the","up"};
System.out.println(
decode(".---.--.-.-.-.--.-...---...-...-...--.-.-..-.--.-............-...-..",
words)
);
}
private static String decode(String code, String[] words){
String[] encodedWords = new String[words.length];
for (int i = 0; i < words.length; i++) {
encodedWords[i] = encodeWord(words[i]);
}
return decodePossibility(code, words, encodedWords, new StringBuilder());
}
private static String decodePossibility(String code, String[] words, String[] encodedWords, StringBuilder current){
if(code.length() == 0) return current.toString();
for (int i = 0; i < encodedWords.length; i++) {
if(code.length() >= encodedWords[i].length()){
if(code.substring(0, encodedWords[i].length()).equals(encodedWords[i])){
String result = decodePossibility(code.substring(encodedWords[i].length()), words, encodedWords, current.append(words[i]).append(' '));
if(result != null){
return result;
}
}
}
}
return null;
}
private static String encodeWord(String word){
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
stringBuilder.append(letters.get(word.charAt(i)));
}
return stringBuilder.toString();
}
Any tips on how to improve the code? Any alternative solution? To back track to a correct solution I would prefer throwing an exception, but sadly I'am not allowed to do so.