804.唯一的摩尔斯密码词(uthash)
心得:思路没有问题,但是没有建立hash的解题想法,导致开始写的代码很复杂。
利用hash键唯一性,自动去重,可以更高效实现个数统计。
#define MAX_STR_LEN 64struct hashitem
{char key[MAX_STR_LEN];UT_hash_handle hh;
};const static char* MORSE[26]={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",\".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--",\"-..-","-.--","--.."};int uniqueMorseRepresentations(char** words, int wordsSize) {struct hashitem* decode=NULL;for(int i=0;i<wordsSize;i++){struct hashitem* pEntry = NULL;int len=strlen(words[i]);int pos=0;char code[MAX_STR_LEN];for(int j=0;j<len;j++){pos+=sprintf(code+pos,"%s",MORSE[words[i][j]-'a']);}HASH_FIND_STR(decode,code,pEntry);if(NULL==pEntry){pEntry=(struct hashitem*)malloc(sizeof(struct hashitem));strcpy(pEntry->key,code);HASH_ADD_STR(decode,key,pEntry);}}int ans=HASH_COUNT(decode);struct hashitem* curr=NULL,*temp=NULL;HASH_ITER(hh,decode,curr,temp){HASH_DEL(decode,curr);free(curr);}return ans;
}
