2023年7月19日 星期三

[290] Word Pattern

感覺是一個對C很不友善的題目(?)
寫完覺得空虛QQ

bool wordPattern(char * pattern, char * s){
char* hash[26];
for (int i=0;i<26; i++)
hash[i]= NULL;

char *token;
/* get the first token */
token = strtok(s, " ");
int idx=0;
/* walk through other tokens */
while( token != NULL )
{
if (idx>=strlen(pattern))
return false;

if (hash[pattern[idx]-'a']==NULL)
{
//check if it already exist on others
for (int i=0;i<26; i++)
{
if ((hash[i]!=NULL)&& (strcmp(hash[i],token)==0))
return false;
}

hash[pattern[idx]-'a']=malloc(sizeof(char)*(strlen(token)+1));
sprintf(hash[pattern[idx]-'a'],"%s", token);
}
else
{
if (strcmp(hash[pattern[idx]-'a'],token)!=0)
return false;
}

idx++;
token = strtok(NULL, " ");
}
if (strlen(pattern)!=idx)
return false;
return true;
}

沒有留言:

張貼留言