llllmz

导航

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

void bulid(int* next,char* s,int n){
    next[0]=-1;
    int index=1,j=-1;
    while(index<n){
        if(j==-1 || s[index-1] ==s[j] ){
            j++;
            next[index++]=j;
        }else{
            j=next[j];
        }
    }
}


int strStr(char* haystack, char* needle) {
    int n1=strlen(haystack),n2=strlen(needle);
    if(n1<n2) return -1;
    int head=0,index=0,tag=-1;
    int* next=(int*)malloc(sizeof(int)*n2);
    bulid(next,needle,n2);
    while(index<n2 && head<n1 ){
        if(haystack[head]==needle[index]){
            head++;
            index++;
            if(index==n2) tag=head-n2;
            printf("%d",head);
        }else{
            index=next[index];
            if(index==-1){
                index=0;
                head++;
            }
        }

    }
    return tag;
}

 

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