现在的位置: 首页 > 综合 > 正文

Implement strStr()

2019年07月26日 ⁄ 综合 ⁄ 共 652字 ⁄ 字号 评论关闭

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

思路:这是非常典型的KMP算法题。

class Solution {
public:
    void computePrefix(char* needle, int* next)
    {
        int m = strlen(needle);
        int i = 0, j = -1;
        next[0] = -1;
        while(needle[i] != '\0')
        {
            while (j >= 0 && needle[j] != needle[i])
            {
                j = next[j];
            }       
            ++i, ++j;
            next[i] = j;
        }        
    }    
    char *strStr(char *haystack, char *needle) {
        if (strcmp(haystack, needle) == 0)
        {
            return haystack;
        }    
        int m = strlen(needle);
        int n = strlen(haystack);
        if (m == 0)
        {
            return haystack;
        }    
        int next[m];
        int i = 0, j = 0;
        computePrefix(needle, next);
        while(haystack[i] != '\0')
        {
            while(j >= 0 && haystack[i] != needle[j])
             j = next[j];
            ++i, ++j;
            if (needle[j] == '\0')
            {
                return haystack + i - j;
            }        
        }        
        return NULL;    
    }
};
【上篇】
【下篇】

抱歉!评论已关闭.