LeetCode 28. Implement strStr()

Implement strStr().

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


It is pretty hard to generalize KMP algorithm under stress and limited time. Better to formalize brute force first and then move forward to KMP.

#include <string>
#include <iostream>
#include <vector>
using namespace std;

// brute force
int strStr(string haystack, string needle) {
    int m = haystack.size();
    int n = needle.size();
    int i = 0, j = 0;
    while(i < m && j < n) {
        if(haystack[i] == needle[j]) {
            i++;
            j++;
        } else {
            i = i - j + 1;
            j = 0;
        }
    }
    return j == n ? i - j : -1;
} // time complexity: O(m*n)


// KMP to make the time complexity to be O(m + n);
vector<int> next(string& needle) {
    vector<int> next(needle.size(), 0);
    for(int i = 1; i < needle.size(); ++i) {
        int j = next[i-1];
        while(j > 0 && (needle[i] != needle[j])) j = next[j-1];
        next[i] = (j + (needle[i] == needle[j]));
    }
    return next;
}

int strStrII(string haystack, string needle) {
    vector<int> nextV = next(needle);
    int k = 0;
    for(int i = 0; i < haystack.size(); ++i) {
        while(k > 0 && haystack[i] != needle[k]) k = nextV[k-1];
        if(haystack[i] == needle[k]) k++;
        if(k == needle.size()) return i - needle.size() + 1;
    }
    return -1;
}


你可能感兴趣的:(LeetCode 28. Implement strStr())