//建立字符串数组morse,存放words中的字符串转成莫尔斯密码后的字符串,
//每次处理words中的字符串,如果不重复,就添加到morse里面,最终输出morse中字符串的个数
#include <stdio.h> #include <string.h> #include <stdlib.h> int uniqueMorseRepresentations(char ** words, int wordsSize); int main() { int i,k,num ; char ** str =(char **)malloc(sizeof(char*)*100); for(i=0;i<100;i++) { str[i]=(char *)malloc(sizeof(char)*100); } i=0; while(scanf("%s",str[i])!=EOF) { i++; } num=uniqueMorseRepresentations(str, i) ; printf("%d",num); /* for(k=0;k<i;k++) { printf("%s\n",str[k]); }*/ } //建立字符串数组morse,存放words中的字符串转成莫尔斯密码后的字符串, //每次处理words中的字符串,如果不重复,就添加到morse里面,最终输出morse中字符串的个数 int uniqueMorseRepresentations(char ** str, int wordsSize) { char dict[26][5]={".-","-...","-.-.","-..",".","..-.","--.","....","..", ".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-", "...-",".--","-..-","-.--","--.."}; char morse[100][60]={"\0"}; int count=0 ; for(int i=0;i<wordsSize;i++) { char tmp[60]={"\0"}; int flag = 0; for(int j=0;j<strlen(str[i]);j++) { //把 src 所指向的字符串追加到 dest 所指向的字符串的结尾 //比如第一个串是gin, g-'a'=103-97=6-->对应的dict[6]="--." strcat(tmp,dict[str[i][j]-'a']); } for(int k=0;k<count;k++) { if(strcmp(morse[k],tmp)==0) { flag =1; break; } } if(flag==0) { strcpy(morse[count],tmp); count++; } } return count ; }
方法二:JAVA 哈希集合
class Solution { public int uniqueMorseRepresentations(String[] words) { String[] MORSE = new String[]{".-","-...","-.-.","-..",".","..-.","--.", "....","..",".---","-.-",".-..","--","-.", "---",".--.","--.-",".-.","...","-","..-", "...-",".--","-..-","-.--","--.."}; Set<String> seen = new HashSet(); for (String word: words) { StringBuilder code = new StringBuilder(); for (char c: word.toCharArray()) code.append(MORSE[c - 'a']); seen.add(code.toString()); } return seen.size(); } } 作者:LeetCode 链接:https://leetcode-cn.com/problems/unique-morse-code-words/solution/wei-yi-mo-er-si-mi-ma-ci-by-leetcode/