首页 > 代码库 > LeetCode:Implement strStr()

LeetCode:Implement strStr()


Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if

needle is not part of haystack.


解题思路:

    strstr()函数隶属标准库string.h头文件,其内部的实现是O(n^2)的时间复杂度.在大师

克努特等人发明了KMP算法过后,关于strstr()函数的实现的时间复杂度就是线性的.对于KMP

算法的理解,网上的文章一大堆,这里就不做具体解释.


解题代码:

class Solution 
{
public:
    char *strStr(char *haystack, char *needle) 
    {
        const int n = strlen(haystack), m = strlen(needle);        
        if (!m)
            return haystack;
        int next[m], i, j;
        next[i = 0] = j = -1;
        //求取next数组
        while (i < m - 1)
        {
            if (j == -1 || needle[i] == needle[j])
                next[++i] = ++j;
            else
                j = next[j];
        }
        //模式匹配
        for (i = j = 0; i < n;)
        {
            if (j == -1 || haystack[i] == needle[j])
                ++i, ++j;
            else
                j = next[j];
            if (j == m)
                return haystack + i - m;
        }
        return NULL;
    }
};