KMP(王道)思想,next数组为默认XXXXY类型的子串

C++代码

typedef struct SString
{
    char ch[100] ;
    int length=0;
    SString *i;
    SString *j;
};
void CreateSString(SString& s1) 
{
    
    char m;
    int n;
    cout << "请输入主串长度" << endl;
    cin >> n;
    
    for (int i = 1; i < n+1; i++)
    {
        cout << "请输入" << i << "个数" << endl;
        cin >> m;
        s1.ch[i] = m;
        s1.length++;
    }
    cout << "主串为:";
    for (int i = 1; i < n+1; i++)
    {
        cout << s1.ch[i];
    }
    
}
void CreateSString1(SString& s2)
{
    ;
    char x;
    int y;
    cout << "请输入子串长度" << endl;
    cin >> y;
    for (int i = 1; i < y+1; i++)
    {
        cout << "请输入" << i  << "个数" << endl;
        cin >> x;
        s2.ch[i] = x;
        s2.length++;
    }
    cout << "子串为:";
    for (int i = 1; i < y+1; i++)
    {
        cout << s2.ch[i];
    }
    
}
int Index(SString s1, SString s2)
{
    int j=1, i = 1;
    while (i <= s1.length && j <= s2.length)
    {
        if (s1.ch[i] == s2.ch[j])
        {
            i++;
            j++;
        }
        else
        {
            i = i - j + 2;
            j = 1;
        }    
    }
    if (j > s2.length)
        return i - s2.length;
    else
        return 0;
}
int Index_SXL(SString s1, SString s2, int next[])
{
    int j=1, i = 1;
    while (i <= s1.length && j <= s2.length)
    {
        if (j==0||s1.ch[i] ==s2.ch[j])
        {
            i++;
            j++;
        }
        else
        {
            j = next[j];
        }
    }
    if (j > s2.length)
        return i - s2.length;
    else
        return 0;
}
int main()
{
    clock_t t1, t2;
    SString s1; 
    CreateSString(s1);
    cout << endl;
    SString s2;
    CreateSString1(s2);
    int next[6] = { 0,0,1,2,3,4};
    cout << endl;
    cout << "垃圾算法:" << endl;
    cout << "该数在字符串第" ;
    t1 = clock();
    for (int i = 0; i < 10000; i++)
    {
     Index(s1, s2);
    }
    cout << Index(s1, s2)<<endl;
    t1 = clock()-t1;
    printf("垃圾算法耗时:% lf", ((float)t1) / CLOCKS_PER_SEC);
    cout << endl;
    cout << "SXL算法:" << endl;
    cout << "该数在字符串第";
    t2 = clock();
    for(int i=0;i<10000;i++)
    {    
        Index_SXL(s1, s2, next);
    }
    cout << Index_SXL(s1, s2, next) << endl;
    t2 = clock() - t2;
    printf("SXL算法耗时:% lf", ((float)t2) / CLOCKS_PER_SEC);
    cout << endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值