zoukankan      html  css  js  c++  java
  • Leetcode题解(九)

    28、Implement strStr()-------KMP算法(*)

    题目

    这道题目其实就是实现KMP算法,并且该算法也是比较经典的算法,需要很好的掌握:

    贴上几个介绍字符串匹配的算法说明链接

    http://www.cnblogs.com/Su-30MKK/archive/2012/09/17/2688122.html

    本题实现代码:

     1 class Solution {
     2 public:
     3     int strStr(string haystack, string needle) {
     4          if("" == needle)
     5             return 0;
     6         if("" == haystack )
     7             return -1;
     8        
     9         return kmp(haystack,needle);
    10 
    11     }
    12     int kmp(const std::string& s, const std::string& p, const int sIndex = 0)
    13     {
    14         std::vector<int>next(p.size());
    15         getNext(p, next);//获取next数组,保存到vector中
    16 
    17         int i = sIndex, j = 0;
    18         while(i != s.length() && j != p.length())
    19         {
    20             if (j == -1 || s[i] == p[j])
    21             {
    22                 ++i;
    23                 ++j;
    24             }
    25             else
    26             {
    27                 j = next[j];
    28             }
    29         }
    30 
    31         return j == p.length() ? i - j: -1;
    32     }
    33     void getNext(const std::string &p, std::vector<int> &next)
    34     {
    35         next.resize(p.size());
    36         next[0] = -1;
    37 
    38         int i = 0, j = -1;
    39 
    40         while (i != p.size() - 1)
    41         {
    42             //这里注意,i==0的时候实际上求的是next[1]的值,以此类推
    43             if (j == -1 || p[i] == p[j])
    44             {
    45                 ++i;
    46                 ++j;
    47                 next[i] = j;
    48             }
    49             else
    50             {
    51                 j = next[j];
    52             }
    53         }
    54     }
    55 };
  • 相关阅读:
    react-dnd例子代码学习记录
    GitKraken使用记录
    Table-dnd-tree代码分析
    umi-request请求码200,但是response是网页
    MyBatis-Plus配置输出日志
    PAT甲级1021解法
    PAT甲级1020解法
    PAT甲级1019解法
    PAT甲级1017解法
    PAT甲级1018解法
  • 原文地址:https://www.cnblogs.com/LCCRNblog/p/5037003.html
Copyright © 2011-2022 走看看