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

int change(char c){
    return c-'a';
}

bool judge(char* s,int head,int tail,int n,int* tempp,int* temps){
    if(tail>=n) return false;
    for(int i=head;i<=tail;i++){
        int t=change(s[i]);
        if(temps[t]!=tempp[t]) return false;
    }
    return true;
}


int* findAnagrams(char * s, char * p, int* returnSize){
    int temps[27]={0};
    int tempp[27]={0};
    *returnSize=0;
    int ns=strlen(s),np=strlen(p);
    if(ns<np) return NULL;
    int* array=(int*)malloc(sizeof(int)*(ns));
    for(int i=0;i<np;i++){
        int t=change(p[i]);
        tempp[t]++;
    }
    int head=0,tail=np-1;
    for(int i=head;i<=tail;i++){
        int t=change(s[i]);
        temps[t]++;
    }
    while(tail<ns){
        if(judge(s,head,tail,ns,tempp,temps)){
            array[(*returnSize)++]=head;
        }
        if(tail==ns-1) return array;
        temps[change(s[++tail])]++;
        temps[change(s[head++])]--;   
    }
    return array;
}

力扣独有得全局变量不给多次初始化,真坑啊。

结果:

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。