欢迎光临
我们一直在努力

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

/**
 * 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;
}

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

结果:

未经允许不得转载:大有博文 » 438. 找到字符串中所有字母异位词c
分享到: 更多 (0)

大前端WP主题 更专业 更方便

联系我们联系我们