题目描述:
国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: “a” 对应 “.-”, “b” 对应 “-…”, “c” 对应 “-.-.”, 等等。
为了方便,所有26个英文字母对应摩尔斯密码表如下:
[".-","-…","-.-.","-…",".","…-.","–.","…","…",".—","-.-",".-…","–","-.","—",".–.","–.-",".-.","…","-","…-","…-",".–","-…-","-.–","–…"]
给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,“cab” 可以写成 “-.-…–…”,(即 “-.-.” + “.-” + “-…” 字符串的结合)。我们将这样一个连接过程称作单词翻译。
返回我们可以获得所有词不同单词翻译的数量。
例如:
输入: words = [“gin”, “zen”, “gig”, “msg”]
输出: 2
解释:
各单词翻译如下:
“gin” -> “–…-.”
“zen” -> “–…-.”
“gig” -> “–…--.”
“msg” -> “–…--.”
共有 2 种不同翻译, “–…-.” 和 “–…--.”.
注意:
单词列表words 的长度不会超过 100。
每个单词 words[i]的长度范围为 [1, 12]。
每个单词 words[i]只包含小写字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-morse-code-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答:
int uniqueMorseRepresentations(char ** words, int wordsSize){
int i = 0;
int j = 0;
int n = 0;
int k = 0;
int count = 0;
char tmp[100][100] = {0};
char result[120][100] = {0};
int flag = 0;
char res[26][10] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
for(i = 0; i < wordsSize;i++){
j = 0;
flag = 0;
while(words[i][j] != '\0'){
n = words[i][j] - 'a';
strcat(tmp[i], res[n]); //每一行拼接到tmp[i]中
j++;
}
for(k = 0; k < count; k++) {
if(0 == strcmp(result[k], tmp[i])){ //若摩尔斯密码存在则退出
flag = 1;
break;
}
}
if (0 == flag){
strcpy(result[count], tmp[i]); //若摩尔斯密码不存在则保存至result
count++;
}
}
return count;
}
运行结果: