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日

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失