思路使用 数组保存 字符串的特征值
代码
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int judge(int *a,int *b){
for (int i=0 ;i<26 ;i++){
if (a[i]!=b[i])
return 0 ;
}
return 1 ;
}
int * findAnagrams(char * s, char * p, int * returnSize) {
int sLen = strlen(s);
int pLen = strlen(p);
*returnSize = 0 ;
int *res;
if (sLen < pLen){
return res;
}
res = (int *)malloc(sizeof(int )*sLen);
int pHash[26 ] = {0 };
int sHash[26 ] = {0 };
for (int i=0 ;i<sLen;i++)
sHash[s[i]-'a' ]++;
for (int i=0 ;i<pLen;i++){
if (sHash[p[i]-'a' ] == 0 ){
return res;
}
pHash[p[i]-'a' ]++;
}
memset(sHash,0 ,26 *sizeof(int ));
for (int i=0 ;i<pLen;i++)
sHash[s[i]-'a' ]++;
if (judge(sHash,pHash))
res[(*returnSize)++] = 0 ;
for (int i=1 ;i<sLen-pLen+1 ;i++){
sHash[s[i-1 ]-'a' ]--;
sHash[s[i+pLen-1 ]-'a' ]++;
if (judge(sHash,pHash))
res[(*returnSize)++] = i;
}
return res;
}
理解 onedrive