Leetcode ---利用KMP實現strstr

 https://www.cnblogs.com/zhangtianq/p/5839909.html

#include <iostream>
#include <string.h>
using namespace std;
/**
 * @brief:LeetCode---strstr KMP算法實現
 * @date:2020-3-16
 */
class  Solution{
public:
    /*text、pattern*/
    int strstr(const string &haystack,const string &needle)
    {
        return kmp(haystack.c_str(),needle.c_str());
    }
private:
    /*計算前後綴*/
    static void compute_prefix(const char *pattern,int next[])
    {
        int i;
        int j=-1;
        const int m=strlen(pattern);
        next[0]=j;
        /*計算next:即下一步要走的步數*/
        for(i=1;i<m;i++){
            while(j>-1&&pattern[j+1]!=pattern[i]) j=next[j];//回溯
            if(pattern[j+1]==pattern[i]) j++;
            next[i]=j;

        }
    }
/*KMP 算法實現*/
  static int kmp(const char *text,const char *pattern)
  {
      int i;
      int j=-1;
      const int n=strlen(text);
      const int m=strlen(pattern);
      if(m==0&&n==0)  return 0;
      if(m==0)   return 0;
      int *next=(int *)malloc(sizeof(int)*m);
      compute_prefix(pattern,next);/*得到next數組*/
      /*遍歷主串*/
      for(i=0;i<n;i++){
          while(j>-1&&pattern[j+1]!=text[i]) j=next[j];
          if(text[i]==pattern[j+1]) j++;
          if(j==m-1){
              free(next);
              return i-j;
          }
      }
      free(next);
      next=NULL;
      return -1;
  }
public:
   int res;
};
/**
 * @brief The Solution2 class(採用)
 */
class  Solution2{
public:
    int strstr(const char *haystack,const char *needle)
    {
        int i=0;
        int j=0;
        int m=strlen(haystack);
        int n=strlen(needle);
        while(i<m&&j<n){
            if(haystack[i]==needle[j]){
                i++;
                j++;
            }else{
                i=i-(j-1);
                j=0;
            }

        }
        /*如果匹配成功*/
        if(j==n){
            return i-j;
        }else{
            return -1;
        }
    }
public :
    int res2;
};
/**
 * @brief main[主要是進行測試]
 * @param argc:NULL  命令行參數的個數
 * @param argv:NULL  主要是在數組中進行參數的存儲
 * @return
 */
int main(int argc, char *argv[])
{
    Solution  sol;
    sol.res =sol.strstr(string("he2llo"), string("ll"));
    cout<<sol.res<<endl;

    Solution2  sol2;
    sol2.res2=sol2.strstr("he2llo", "ll");
     cout<<sol.res<<endl;
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章