Morse Code
This program aims to transfer characters to morse code. It will read in a word String array and then return the number of different transformations among all words.
My solution
class Solution {
public int uniqueMorseRepresentations(String[] words) {
HashMap<Character, String> hashMap = new HashMap<Character, String>();
hashMap.put('a', ".-");
hashMap.put('b', "-...");
hashMap.put('c', "-.-.");
hashMap.put('d', "-..");
hashMap.put('e', ".");
hashMap.put('f', "..-.");
hashMap.put('g', "--.");
hashMap.put('h', "....");
hashMap.put('i', "..");
hashMap.put('j', ".---");
hashMap.put('k', "-.-");
hashMap.put('l', ".-..");
hashMap.put('m', "--");
hashMap.put('n', "-.");
hashMap.put('o', "---");
hashMap.put('p', ".--.");
hashMap.put('q', "--.-");
hashMap.put('r', ".-.");
hashMap.put('s', "...");
hashMap.put('t', "-");
hashMap.put('u', "..-");
hashMap.put('v', "...-");
hashMap.put('w', ".--");
hashMap.put('x', "-..-");
hashMap.put('y', "-.--");
hashMap.put('z', "--..");
List<String> morseList = new ArrayList<String>();
for(int i = 0; i < words.length; i++) {
String str = "";
String word = words[i];
for(int j = 0; j < word.length(); j++)
str += (hashMap.get(word.charAt(j)));
System.out.println("\"" + word + "\"" + " -> " + "\"" + str + "\"");
if (!morseList.contains(str))
morseList.add(str);
}
return morseList.size();
}
}
Official solution
class Solution {
public int uniqueMorseRepresentations(String[] words) {
String[] MORSE = new String[]{".-","-...","-.-.","-..",".","..-.","--.",
"....","..",".---","-.-",".-..","--","-.",
"---",".--.","--.-",".-.","...","-","..-",
"...-",".--","-..-","-.--","--.."};
Set<String> seen = new HashSet();
for (String word: words) {
StringBuilder code = new StringBuilder();
for (char c: word.toCharArray())
code.append(MORSE[c - 'a']);
seen.add(code.toString());
}
return seen.size();
}
}
Summary
- The connection between the 26 letters of the English alphabet and the MORSE array could be MORSE[characer - 'a'];
- Use Set to differentiate its elements, so ArrayList here is unnecessary.
网友评论