【LeetCode】28. Implement strStr() (2 solutions)

Implement strStr()

Implement strStr().

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

解法一:暴力解

class Solution {
public:
    int strStr(string haystack, string needle) {
        int m = haystack.size();
        int n = needle.size();
        for(int i = 0; i <= m-n; i ++)
        {
            int j;
            for(j = 0; j < n; j ++)
            {
                if(haystack[i+j] != needle[j])
                    break;
            }
            if(j == n)
                return i;
        }
        return -1;
    }
};

解法二:标准KMP算法。可参考下文。

KMP算法详解

(1)先对模式串needle做“自匹配”,即求出模式串前缀与后缀中重复部分,将重复信息保存在next数组中。

(2)依据next数组信息,进行haystack与needle的匹配。

class Solution {
public:
    int strStr(char *haystack, char *needle) {
        int hlen = strlen(haystack);
        int nlen = strlen(needle);
        int* next = new int[nlen];
        getNext(needle, next);
        int i = 0;
        int j = 0;
        while(i < hlen && j < nlen)
        {
            if(j == -1 || haystack[i] == needle[j])
            {// match current position, go next
                i ++;
                j ++;
            }
            else
            {// jump to the previous position to try matching
                j = next[j];
            }
        }
        if(j == nlen)
        // all match
            return i-nlen;
        else
            return -1;
    }
    void getNext(char *needle, int next[])
    {// self match to contruct next array
        int nlen = strlen(needle);
        int j = -1;     // slow pointer
        int i = 0;      // fast pointer
        next[i] = -1;    //init next has one element
        while(i < nlen-1)
        {
            if(j == -1 || needle[i] == needle[j])
            {
                j ++;
                i ++;           //thus the condition (i < nlen-1)
                next[i] = j;    //if position i not match, jump to position j
            }
            else
            {
                j = next[j];    //jump to the previous position to try matching
            }
        }
    }
};

原文地址:https://www.cnblogs.com/ganganloveu/p/3753981.html