getNext是KMP算法找next的方法,getBetterNext是KMP改进方法。
    这个算法的核心想法就是在匹配的时候不走回头路

    1. #include <iostream>
    2. #include <vector>
    3. #include <string>
    4. int IndexKMP(std::string SrcStr, std::string tgtStr, int startIdx);
    5. void getNext(std::string tgtStr, std::vector<int>& next);
    6. void getBetterNext(std::string tgtStr, std::vector<int>& next);
    7. int main()
    8. {
    9. std::string src = "Haymwanx_wangaAAAAAAAabziteng";
    10. std::string tgt = "aAAAAAAAab";
    11. std::cout << IndexKMP(src, tgt, 0);
    12. }
    13. int IndexKMP(std::string SrcStr, std::string tgtStr, int startIdx) {
    14. int i = startIdx;
    15. int j = 0;
    16. std::vector<int> next(255);
    17. getNext(tgtStr, next);
    18. for (int i = 0; i < next.size(); i++) {
    19. std::cout << next[i] << ' ';
    20. }
    21. std::cout << std::endl;
    22. getBetterNext(tgtStr, next);
    23. for (int i = 0; i < next.size(); i++) {
    24. std::cout << next[i] << ' ';
    25. }
    26. while (i < SrcStr.size() && j < tgtStr.size()) {
    27. if (SrcStr[i] == tgtStr[j]) {
    28. ++j;
    29. ++i;
    30. }
    31. else if (j==0){
    32. ++i;
    33. j = next[j];
    34. }
    35. else {
    36. j = next[j];
    37. }
    38. }
    39. if (j >= tgtStr.size()) {
    40. return i - tgtStr.size();
    41. }
    42. else {
    43. return 0;
    44. }
    45. }
    46. void getBetterNext(std::string tgtStr,std::vector<int>& next) {
    47. int i = 1, j = 0;
    48. next[0] = 0;
    49. while (i < tgtStr.size()) {
    50. if (j == 0 || tgtStr[i] == tgtStr[j]) {
    51. if (tgtStr[i] == tgtStr[j]) {
    52. next[i] = next[j];
    53. }
    54. else {
    55. next[i] = j;
    56. }
    57. ++i; ++j;
    58. }
    59. else {
    60. j = next[j];
    61. }
    62. }
    63. }
    64. void getNext(std::string tgtStr, std::vector<int>& next) {
    65. int i = 1, j = 0;
    66. next[0] = 0;
    67. while (i < tgtStr.size()) {
    68. if (j == 0 || tgtStr[i] == tgtStr[j]) {
    69. next[i] = j;
    70. ++i; ++j;
    71. }
    72. else {
    73. j = next[j];
    74. }
    75. }
    76. }