Leetcode之KMP字符串算法

针对题目28题 实现strStr()功能找出needle在haystack字符串的第一个位置 否则返回-1

当然有暴力法,但是时间复杂度是O(mn)

而KMP算法提前计算出needle字符串的重复数据加以利用,j能够有效的回退到可能的位置,时间复杂度是O(m+n)

int strStr(string haystack, string needle) {
        int n = haystack.size(), m = needle.size();
        if(m == 0) return 0;
        if(n == 0) return -1;
        vector<int> next(m);
        next[0] = -1;
        int j = 0, k = -1;
        while(j < m-1)
        {
            if(k == -1 || needle[j] == needle[k])
            {
                if(needle[++j] == needle[++k])
                {
                    next[j] = next[k];
                }
                else
                    next[j] = k;
            }
            else
                k = next[k];
        }
        int i = 0;
        j = 0;
        while(i < n && j < m)
        {
            if(j==-1 || haystack[i] == needle[j])
            {
                i++;
                j++;
            }
            else
                j = next[j];
        }
        if(j == m)
            return i - j;
        else
            return -1;

    }

next数组用来存储当needle字符串j位置不符时应该跳转的位置,反映的是needle[0, ... j-1]中重复的数据,当然为了更进一步提高效率,例如needle [abab]与haystack [abac],最后一个字符b!=c不相等时,显然上一个也是b,因此next[j] = next[k],如果needle出现连续重复串时多跳一次。

如果字符相等则 i与j同时后移。,否则i不变,j到上一个位置。

详情参考https://www.cnblogs.com/yjiyjige/p/3263858.html

猜你喜欢

转载自blog.csdn.net/li4692625/article/details/119026170