Title: Unique Morse Code
content:
The International Morse Code defines a standard encoding method, where each letter corresponds to a string consisting of a series of dots and dashes, for example: "a" corresponds to ".-", "b" corresponds to "-...", " c" corresponds to "-.-.", etc.
For convenience, the Morse code table for all 26 English letters is as follows:
[".-","-…","-.-.","-…",".","…-.","–.","…","…",".—","-.-",".-…","–","-.","—",".–.","–.-",".-.","…","-","…-","…-",".–","-…-","-.–","–…"]
Given a list of words, each word can be written as a combination of Morse code for each letter. For example, "cab" can be written as "-.-…–…", (ie, a combination of "-.-." + ".-" + "-..."). We call such a connection process a word translation.
Return we can get the number of different word translations for all words.
For example:
Input: words = [“gin”, “zen”, “gig”, “msg”]
Output: 2
Explanation:
The translation of each word is as follows:
“gin” -> “–…-.”
“zen” -> “ –…-."
"gig" -> "–…--."
"msg" -> "–…--."
There are 2 different translations, “–…-.” and “–…--.”.
note:
单词列表words 的长度不会超过 100。
每个单词 words[i]的长度范围为 [1, 12]。
每个单词 words[i]只包含小写字母。
Source: LeetCode
Link: https://leetcode-cn.com/problems/unique-morse-code-words
answer
int uniqueMorseRepresentations(char ** words, int wordsSize){
int b,c;
// 把字母对应情况用二元组来表示
char a[26][5]={
".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
// hashmap用来存储不重复的单词所对应的摩尔斯密码
char hashmap[100][60]={
0};//不初始化,会导致程序bug,改了好久才发现这里出问题,好习惯一定要养成
int count=0;
//二维字符用来存储每个单词对应的摩尔斯密码 12x4=48
char z[100][48] = {
0};
for(int i=0;i<wordsSize;i++){
for(int j=0;j<strlen(words[i]);j++){
//b用来表示这个单词中某个字母和a间的差,是a的话,差是0,b的话差是1,用b的值来对应每个单词摩尔斯码
b=words[i][j]-'a';
//把每个摩尔斯码拼接到对应的第i个单词那个
strcat(z[i],a[b]);
}
//循环遍历hashmap中的字符串去比较,有相等则break,跳出的时候c一定不可能大于count,没有相同的时候c>count;
for(c=0;c<=count;c++){
if(strcmp(hashmap[c],z[i])==0){
break;
}
}
//不同字符串的时候往hashmap中添加
if(c>count){
strcat(hashmap[c],z[i]);
count++;
}
}
return count;
}
note:
It is a good habit to remember to initialize each time you declare a variable. Also, when you use the string strcmp strcat strcpy, you must type it correctly, remember not to make a mistake.
to sum up:
Build a hashmap to check duplication. It is found that python's collection dictionaries have the effect of preventing duplication. These are all encapsulated. C language needs to be implemented through code to prevent duplication. So I think C language is very good for practicing algorithms. Go implement some low-level things yourself.