国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: “a” 对应 “.-”, “b” 对应 “-…”, “c” 对应 “-.-.”, 等等。
为了方便,所有26个英文字母对应摩尔斯密码表如下:
[".-","-…","-.-.","-…",".","…-.","–.","…","…",".—","-.-",".-…","–","-.","—",".–.","–.-",".-.","…","-","…-","…-",".–","-…-","-.–","–…"]
给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,“cab” 可以写成 “-.-…–…”,(即 “-.-.” + “-…” + ".-"字符串的结合)。我们将这样一个连接过程称作单词翻译。
返回我们可以获得所有词不同单词翻译的数量。
例如:
输入: words = [“gin”, “zen”, “gig”, “msg”]
输出: 2
解释:
各单词翻译如下:
“gin” -> “–…-.”
“zen” -> “–…-.”
“gig” -> “–…--.”
“msg” -> “–…--.”
共有 2 种不同翻译, “–…-.” 和 “–…--.”.
注意:
单词列表words 的长度不会超过 100。
每个单词 words[i]的长度范围为 [1, 12]。
每个单词 words[i]只包含小写字母。
使用二分搜索树实现
public class Solution {
//使用二分搜索树来实现
private class BST<E extends Comparable<E>> {
//定义一个二叉树
private class Node {
public E e;
public Node left, right;
public Node(E e) {
this.e = e;
left = null;
right = null;
}
}
//定义root和size的成员变量
private Node root;
private int size;
public BST(){
root = null;
size = 0;
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
// 向二分搜索树中添加新的元素e
public void add(E e){
if(root == null){
root = new Node(e);
size ++;
}
else
add(root, e);
}
// 向以node为根的二分搜索树中插入元素e,递归算法
private void add(Node node, E e){
if(e.equals(node.e))
return;
else if(e.compareTo(node.e) < 0 && node.left == null){
node.left = new Node(e);
size ++;
return;
}
else if(e.compareTo(node.e) > 0 && node.right == null){
node.right = new Node(e);
size ++;
return;
}
if(e.compareTo(node.e) < 0)
add(node.left, e);
else //e.compareTo(node.e) > 0
add(node.right, e);
}
}
public int uniqueMorseRepresentations(String[] words) {
String[] codes = {
".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
BST<String> bst = new BST<>();
for(String word: words){
StringBuilder res = new StringBuilder();
for(int i = 0 ; i < word.length() ; i ++)
//word.charAt(i)获取指定索引的字符
res.append(codes[word.charAt(i) - 'a']); //每一个位置的索引即为对应的字符的ascii码减去'a'的ascii码(97)
将res对象的字符串添加到二分搜索树的时候,按照ascii的值进行比较
bst.add(res.toString());
}
//返回该二分搜素树节点的数量
return bst.size();
}
}
使用Set集合来实现
利用set集合有序的特点
public class Solution{
public int uniqueMorseRepresentations(String[] words) {
String[] codes = new String[]{
".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--.."};
Set<String> seen = new HashSet();
for (String word : words) {
StringBuilder code = new StringBuilder();
for (char c : word.toCharArray())//将字符中的数据以字符数组的形式返回
code.append(codes[c - 'a']);
seen.add(code.toString());
}
return seen.size();
}
}