• KMP算法(C++)


           KMP算法与BF算法不一样的在于,当主串与子串不匹配时,主串不回溯,选择了子串回溯,大大提高了运算效率。

           借用了next1【】数组,让子串回溯。get_next函数求next1【】数组,get_next函数的实现难点在于下列几行代码:

    while (i < T.length)
        {
            if (j == 0 || T.ch[i] == T.ch[j])
            {
                ++i,  ++j;
                next1[i] = j;
            }
            else
                j = next1[j];
        }

             只要明确两点就容易理解:

    1、Tj == Tnext[j],那么next[j+1]的最大值为next[j]+1。

    2、Tj != Tnext[j],那么next[j+1]可能的次最大值为next[ next[j] ]+1,以此类推即可求出next[j+1]。

    1. #include
    2. #include
    3. using namespace std;
    4. int next1[1000];
    5. typedef struct node
    6. {
    7. char ch[251];
    8. int length=0;//串当前长度
    9. }SString;
    10. void get_next(SString T)
    11. {
    12. int i = 1;//当前串正在匹配字符串位置,也是next数组的索引
    13. next1[1] = 0;
    14. int j = 0;
    15. while (i < T.length)
    16. {
    17. if (j == 0 || T.ch[i] == T.ch[j])
    18. {
    19. ++i;
    20. ++j;
    21. next1[i] = j;
    22. }
    23. else
    24. j = next1[j];
    25. }
    26. }
    27. int Index_KMP(SString S, SString T, int pos)//S主串,T子串,pos从主串pos位置开始匹配
    28. {
    29. int i = pos, j = 1;//i为主串下标,j为子串下标
    30. while (i <= S.length && j <= T.length)
    31. {
    32. if (S.ch[i] == T.ch[j])//匹配,往下继续
    33. {
    34. i++;
    35. j++;
    36. }
    37. else
    38. j=next1[j];
    39. }
    40. if (j >= T.length) return i - T.length;//返回主串与子串匹配时,主串的第一个下标
    41. else return 0;
    42. }
    43. int main()
    44. {
    45. SString s;
    46. SString t;
    47. cout << "输入主串长度:" ;
    48. cin >> s.length;
    49. cout << endl;
    50. cout << "输入子串长度:";
    51. cin >> t.length;
    52. cout << endl << "输入主串:";
    53. for (int i = 1; i <= s.length; i++)//从下标1开始储存
    54. {
    55. cin >> s.ch[i];
    56. }
    57. cout << endl << "输入子串:";
    58. for (int i = 1; i <= t.length; i++)
    59. {
    60. cin >> t.ch[i];
    61. }
    62. get_next(t);
    63. int a = Index_KMP(s, t, 1);
    64. cout <
    65. }

  • 相关阅读:
    jQuery小结二
    java毕业设计蛋糕店会员系统Mybatis+系统+数据库+调试部署
    第六章 图论 16 AcWing 1558. 加油站
    Linux Centos7安装后,无法查询到IP地址,无ens0,只有lo和ens33的解决方案
    Qt 自定义提示框 类似QMessageBox
    修改git tag的描述信息
    【动态规划】139. 单词拆分、多重背包
    【安全】网络安全态势感知
    python经典百题之利用ellipse and rectangle 画图
    9、ajax和json
  • 原文地址:https://blog.csdn.net/qq_74156152/article/details/132924904