Monday, November 25, 2013

LeetCode Problem : Implement strStr()

Problem


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

Code

vector<int> KMP_Prefix(const string& pattern,int m)
{
    int k = 0;
    vector<int> H(m);
    H[0] = 0;
    for(int i = 1;i < m;++i){
        while(k > 0 && pattern[k] != pattern[i])
            k = H[k - 1];
        if(pattern[k] == pattern[i])
            ++k;
        H[i] = k;
    }
    return H;
}

int kmp(const string& text,const string& pattern,const vector<int>& H,int m,int n)
{
    int i = 0,j = 0;
    while(i < n){
        if(text[i] == pattern[j]){
            ++i;
            ++j;
            if(j == m){
                return (i - m);
            }
        }
        else{
            if(j == 0)
                ++i;
            else
            j = H[j - 1];
        }
    }
    return -1;
}
char *strStr(char *haystack, char *needle) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    int n = strlen(haystack);
    int m = strlen(needle);
    if(n == 0 && m == 0)
        return "";
    if(m == 0)
        return haystack;
    if(m > n)
        return 0;
    vector<int> vret = KMP_Prefix(needle,m);
    int ret = kmp(haystack,needle,vret,m,n);
    if(ret == -1)
        return 0;
    return (haystack + ret);
}

No comments:

Post a Comment