题目:
国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如:
'a' 对应 ".-" ,
'b' 对应 "-..." ,
'c' 对应 "-.-." ,以此类推。
为了方便,所有 26 个英文字母的摩尔斯密码表如下:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
给你一个字符串数组 words ,每个单词可以写成每个字母对应摩尔斯密码的组合。
例如,"cab" 可以写成 "-.-..--..." ,(即 "-.-." + ".-" + "-..." 字符串的结合)。我们将这样一个连接过程称作 单词翻译 。
对 words 中所有单词进行单词翻译,返回不同 单词翻译 的数量。
示例 1:
输入: words = ["gin", "zen", "gig", "msg"]
输出: 2
解释:
各单词翻译如下:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
共有 2 种不同翻译, "--...-." 和 "--...--.".
示例 2:
输入:words = ["a"]
输出:1
提示:
1 <= words.length <= 100
1 <= words[i].length <= 12
words[i] 由小写英文字母组成
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-morse-code-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
结果:
解题思路:
很暴力的解决方法:
1、将所有单词转换成福尔摩斯密码
2、去重,通过将完全互不相同的福尔摩斯序号存储到notSame数组中,从这个数组的成员个数就可以知道总共有多少个互不相同的。
代码:
void *GetHolmesStr(char *words, char *hoWords)
{
char holmes[26][5] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
int len = strlen(words);
for (int i = 0; i < len; i++) {
strcat(hoWords, holmes[words[i] - 'a']);
}
return;
}
int uniqueMorseRepresentations(char ** words, int wordsSize){
char **hoWords = (char **)malloc(sizeof(char *) * wordsSize);
for (int i = 0; i < wordsSize; i++) {
hoWords[i] = (char *)malloc(sizeof(char ) * 50);
hoWords[i][0] = '\0';
GetHolmesStr(words[i], hoWords[i]);
}
int notSame[100] = {0};
notSame[0] = 1;
int index = 1;
for (int i = 1; i < wordsSize; i++) {
notSame[index++] = i;
for (int j = 0; j < index - 1; j++) {
if (strcmp(hoWords[i], hoWords[notSame[j]]) == 0) {
index--;
break;
}
}
}
return index;
}
这篇博客介绍了LeetCode第804题——唯一摩尔斯密码词的问题。文章详细阐述了如何将英文单词转换为摩尔斯密码,并通过示例解释了单词翻译的过程。解题思路包括使用暴力方法将所有单词转为摩尔斯码并去重,以计算不同的摩尔斯码组合。最后,博客提供了代码实现。
638

被折叠的 条评论
为什么被折叠?



