编辑代码

#include <stdio.h>
int main () {
    //JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
    char str1[] = "abcabeeeabcabc"  //主字符串
    char str2[] = "abcab";          //模式串

    int str1_len = strlen(str1); 
    int str2_len = strlen(str2);
    int next[str2_len];     //创建next数组,长度与模式串相等
    int next_len = sizeof(next) / sizeof(int); //next数组的长度
    next[0] = 0;            //next默认[0]==0

    int j = 0,i = 1;
    //根据模式串str2构建next数组
    while (i < str2_len){
        if(str2[i] == str2[j]){
            next[i] = ++j;
            i++; 
        }else{
            if(j == 0){
                next[i] = 0;
                i++;
            }else{
                j = next[j-1];
            }
        }
    }

    j = 0;
    i = 0;
    //进行匹配字符串
    while (i < str1_len) {
        if (str1[i] == str2[j]) {
            j++;
            i++;
        } else if (j > 0) {
            j = next[j - 1];
        } else {
            i++;
        }
        if (j == next_len) {
            puts("含子串");
            break;
        }
    }
        
//打印next数组
    for(int i = 0;i<str2_len;++i){
        printf("%c",i);
    }

}