覺得應該要會的題目><
malloc 和memset 的用法&放的位置一直喬不好!
刷題之路堪慮XD
題意就是摩斯密碼換成字串~若每個字母的中間不停頓non stop 的串起來的話, 有可能會組出一樣的output 字串. 題目問的就是總共有幾組不同的答案?
為了省事加上懶的再一直算超過範圍了沒, 就先給它全部空間需要的array都宣告好,
但已經想到可以優化的部分是, 每次比對到確定沒有一樣的再加進array裡, 然後return value ++
不過我現在精神不太好XD 先這樣就好~(逃走)
char *Morse[] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
int uniqueMorseRepresentations(char ** words, int wordsSize){
//size <=12 ,4*12=48
char **retArray = malloc(sizeof(char*) * 100);
int i,j,k,retCount = 0;
//check from start , if the same , break. not the same, add in it and ret+1
for (i=0;i<wordsSize; i++)
{
retArray[i] = malloc(sizeof(char)*49);
memset(retArray[i],0,49);
for (j=0; j < strlen(words[i]);j++)
{
int index=0;
index = words[i][j]-97;
strcat(retArray[i],Morse[index]);
}
for (k=0;k<i;k++)
{
if (strcmp(retArray[i],retArray[k]) ==0)
break;
}
if (k==i)
retCount++;
}
return retCount;
}
(第二天更新)改了一下~結果空間沒有比較省啊XD
也沒有比較快, 那我在瞎忙什麼><
char *Morse[] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
int uniqueMorseRepresentations(char ** words, int wordsSize){
//size <=12 ,4*12=48
char **retArray = malloc(sizeof(char*) * 100);
int i,j,k,retCount = 0;
char *tmp = malloc(sizeof(char*) * 49);
//check from start , if the same , break. not the same, add in it and ret+1
for (i=0;i<wordsSize; i++)
{
memset (tmp, 0 , 49);
for (j=0; j < strlen(words[i]);j++)
{
int index=0;
index = words[i][j]-97;
// strcat(retArray[i],Morse[index]);
strcat(tmp,Morse[index]);
}
for (k=0;k<retCount;k++)
{
if (strcmp(tmp,retArray[k]) ==0)
break;
}
if (k==retCount)
{
retArray[retCount]= malloc(sizeof(char*)*49);
memset(retArray[retCount],0,49);
memcpy(retArray[retCount],tmp,strlen(tmp));
retCount++;
}
}
return retCount;
}
原來只要給它array都宣告好就好嗎?(thinking)
看起來空間可以少一點, 但是平均時間似乎沒有每次malloc 當次的array 來的快?!(thinking again XD)
char *Morse[] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
int uniqueMorseRepresentations(char ** words, int wordsSize){
//size <=12 ,4*12=48
char retArray[100][49] = {};
int i,j,k,retCount = 0;
//check from start , if the same , break. not the same, add in it and ret+1
for (i=0;i<wordsSize; i++)
{
for (j=0; j < strlen(words[i]);j++)
{
int index=0;
index = words[i][j]-97;
strcat(retArray[i],Morse[index]);
}
for (k=0;k<i;k++)
{
if (strcmp(retArray[i],retArray[k]) ==0)
break;
}
if (k==i)
retCount++;
}
return retCount;
}
沒有留言:
張貼留言