leetcode oj 28 字符串匹配 kmp 下标从0开始 kuangbin模板

28. Implement strStr()


  • Total Accepted: 146121
  • Total Submissions: 546205
  • Difficulty: Easy
  • Contributors: Admin

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Subscribe to see which companies asked this question

代码:

class Solution {
public: int f[ 150000];

void getfill(string t)
{
  

    f[0]=-1;
    int j=0; 
    int k=-1;
    while(j<t.size())
    
        if(k==-1||t[j]==t[k])
        {
            f[++j]=++k;
        }
        else k=f[k];

}
public:
int strStr(string s,string t)
{
    int slen=s.length();
    int tlen=t.length();

    int i=0;
    int j=0;
    getfill(t);
    while(i<slen&&j<tlen)
    {
        if(j==-1||s[i]==t[j])
        {
            i++;
            j++;
        }
        else j=f[j];
    }
        if(j==tlen)
        return i-tlen;
        else return -1;
         


}
};
    原文作者:KMP算法
    原文地址: https://blog.csdn.net/FengTwoYear/article/details/53690875
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞