llllmz

导航

438. 找到字符串中所有字母异位词c

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

bool judge(int* a,int* b){
    for(int i=0;i<27;i++){
        if(a[i]<b[i]) return false;
    }
    return true;
}

int* findAnagrams(char * s, char * p, int* returnSize){
    int n1=strlen(s),n2=strlen(p);
    *returnSize=0;
    if(n1<n2) return NULL; 
    int ts[27]={0};
    int tp[27]={0};
    int* array=(int*)malloc(sizeof(int)*n1);
    for(int i=0;i<n2;i++){
        tp[p[i]-'a']++;
    }
    for(int i=0;i<n2;i++){
        ts[s[i]-'a']++;
    }
    int head=0,tail=n2-1,count=0;
    while(tail<n1){
        if(judge(ts,tp)){
            array[count++]=head;
        }
        ts[s[head++]-'a']--;
        tail++;
        if(tail<n1) ts[s[tail]-'a']++;    
    }
    *returnSize=count;
    return array;
}

 

posted on 2024-03-18 16:50  神奇的萝卜丝  阅读(17)  评论(0)    收藏  举报