题目:
简述题目:
题目中给出了一个摩斯密码的对应数组,也就是每个字母分别对应的摩斯密码,然后给出一组单词,求最终不同的摩斯密码的个数(因为有些字母的摩斯密码的组合可能会相同)
思路:
遍历,然后生成每个单词的莫斯密码,存储,求个数
我一开始用了hashmap,还统计了每个摩斯密码出现的个数,但是其实并么有这个必要,只需要知道一共有多少个不同的就行了,所以后来改用了hashset,可以直接过滤到相同的元素,最终直接范围set.size()就行了
代码:
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class uniqueMorseRepresentations804 {
public static int uniqueMorseRepresentations(String[] words) {
// 这里使用set
String morseString = "";
String[] morseCode = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
Set<String> set = new HashSet<>();
for(int i = 0; i < words.length; i++){
morseString = "";
for(int j = 0; j < words[i].length();j++){
morseString += morseCode[words[i].charAt(j) - 'a'];
}
set.add(morseString);
}
return set.size();
// 这里用了hashmap
// String morseString = "";
// String[] morseCode = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
// Map<String,Integer> map = new HashMap<>();
// for(int i = 0; i < words.length; i++){
// morseString = "";
// for(int j = 0; j < words[i].length();j++){
// morseString += morseCode[words[i].charAt(j) - 'a'];
// }
// if(map.containsKey(morseString)){
// map.put(morseString, map.get(morseString)+1);
// }else{
// map.put(morseString, 1);
// }
// }
// return map.size();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] words = {"gin", "zen", "gig", "msg"};
System.out.println(uniqueMorseRepresentations(words));
}
}