llllmz

导航

28. 找出字符串中第一个匹配项的下标c

KMP!

void buildnext(int* next,char* s){
    int n=strlen(s);
    for(int i=0;i<n;i++){
        next[i]=pre(s,i);
        printf("%d ",next[i]);
    }
 
}

int pre(char* s,int head){
    if(head==0) return -1;
    if(head==1) return 0;
    int start=0,index=1,count=1;
    while(index<head){
        if(s[index]!=s[start]){
            start=0;
            count++;
            index=start+count;
        }else{
            start++;
            index++;
        }
    }
    return start;
}

int strStr(char* haystack, char* needle) {
    int n1=strlen(haystack),n2=strlen(needle);
    int* next=(int*)malloc(sizeof(int)*n2);
    buildnext(next,needle);
    int index=0,t=0;
    while(t<n2 && index<n1){
        if(haystack[index]==needle[t]){
            index++;
            t++;
        }else{
            t=next[t];
            if(t==-1){
                t=0;
                index++;
            }
        }
    }
    if(t==n2) return index-n2;
    return -1;
}

结果:

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