I异乡人l 2021-08-15 12:56 采纳率: 100%
浏览 48
已结题

自己写的KMP算法,出了点问题


#include<iostream>
#include<string>
using namespace std;

int* get_next(string needle)
{
    int* next = new int[needle.size()];
    int i = 0, j = -1;
    next[0] = -1;
    while (i < needle.size() - 1)
    {
        if (j == -1 || needle[i] == needle[j])
        {
            ++i, ++j;
            next[i] = j;
        }
        else
        {
            j = next[j];
        }
    }
    return next;
}

int KMP(string needle, string haystack)
{
    int* next = get_next(needle);
    int i = 0, j = 0;
    while (i < haystack.size() && j < needle.size())
    {
        if (j == -1 || haystack[i] == needle[j])
        {
            ++i, ++j;
        }
        else
        {
            j = next[j];
        }
    }
    if (j == needle.size())
    {
        return i - j;
    }
    return -2;
}

int main()
{
    string haystack = "abcacbcdf";
    string needle = "acb";
    cout << KMP(haystack, needle);
    return 0;
}

该程序最终返回的是-2,但是按照KMP算法应当返回3,我进行调试发现i = 1, j = -1 时就跳出了while,有点搞不明白为什么,向各位请教一下原因

  • 写回答

1条回答 默认 最新

  • qzjhjxj 2021-08-15 13:41
    关注

    C++中string类size() 函数的返回值是无符号数,所以判断的地方需强制类型转换下,供参考:

    #include<iostream>
    #include<string>
    using namespace std;
    int* get_next(string needle)
    {
        int* next = new int[needle.size()];
        int i = 0, j = -1;
        next[0] = -1;
        while (i < (int)needle.size() - 1)
        {
            if (j == -1 || needle[i] == needle[j])
            {
                ++i, ++j;
                next[i] = j;
            }
            else
            {
                j = next[j];
            }
        }
        return next;
    }
    int KMP(string needle, string haystack)
    {
        int* next = get_next(needle);
        int i = 0, j = 0;
        while (i < (int)haystack.size() && j < (int)needle.size())
        {
            if (j == -1 || haystack[i] == needle[j])
            {
                ++i, ++j;
            }
            else
            {
                j = next[j];
            }
        }
        if (j == (int)needle.size())
        {
            return i - j;
        }
        return -2;
    }
    int main()
    {
        string haystack = "abcacbcdf";
        string needle = "acb";
        cout << KMP(haystack, needle);
        return 0;
    }
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 8月23日
  • 已采纳回答 8月15日
  • 创建了问题 8月15日

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格