L804唯一摩尔斯密码词
GitHub 账户:LuvnJoae 欢迎关注! https://github.com/LuvnJoae
GitHub 代码链接:https://github.com/LuvnJoae/Java_leetcode
思路与结果
代码
思路1
package Day4_4_17.L804;
import java.util.HashMap;
public class Solution {
public int uniqueMorseRepresentations(String[] words) {
// 通过哈希表 键值对 的方式存储摩尔密码和字母的关系
HashMap<Character,String> map1 = new HashMap<>();
String[] ms = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
for (int i = 0; i < 26; i++) {
map1.put((char)('a'+i),ms[i]);
}
// 遍历字符串数组,对每一个字符串,先进行转成字符数组,然后根据单个字符,
// 和哈希表map1内的键值对象,连接构造出一个摩尔字符串,用新的哈希表map2存储
HashMap<String,Integer> map2 = new HashMap<>();
for (int i = 0; i < words.length; i++) {
char[] chars = words[i].toCharArray();
// 这里也可以通过 StringBuild的append的方法实现,详见思路2的代码
String temp = new String();
for (int i1 = 0; i1 < chars.length; i1++) {
temp = temp.concat(map1.get(chars[i1]));
}
// 如果没有这个摩尔字符串,给值1,有的话,不进行任何操作。
if ( !map2.containsKey(temp) ){
map2.put(temp,1);
}
}
// 最后map2中的键值对个数,也就是map2的size,就是答案。
int count = map2.size();
return count;
}
}
思路2
package Day4_4_17.L804;
import java.util.HashSet;
public class Solution2 {
public int uniqueMorseRepresentations(String[] words) {
// 直接通过一个字符串数组存储摩尔码,对应读取的话用字符串数组下标。
String[] strs = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
// 建立哈希表,利用哈希表元素不重复的特点。
HashSet<String> set = new HashSet<>();
for (String word : words) {
// StringBuilder可改变长度,而且apend方法很好用,可以直接在原StringBuilder上追加。
// 就相当于 String 在自身上 concat的方法,而且更省空间。
StringBuilder sB = new StringBuilder();
for (char c : word.toCharArray()) {
sB.append(strs[c - 'a']);//用下标读取对应摩尔码
}
set.add(sB.toString());//定义的Set里是String类型,所以要转换一下
}
int count = set.size();
return count;
}
}