1. 程式人生 > >[Leetcode]28. Implement strStr()

[Leetcode]28. Implement strStr()

題目很簡單,KMP演算法搞定 

class Solution {
public:
     void prekmp(string s,int *next){
        int j = -1;
        int n = s.size();
        next[0] = -1;
        int i = 0;
        while(i < n-1){
            while(j !=-1 && s[i] != s[j]) j=next[j];
            next[++i] = ++j;
        }
     }   
    int kmp(string s, string t, int *next){
        if(s == t) return 0;
        else if(t.size() == 0) return 0;
        int j = 0;
        int i;
        for(i = 0; i < s.size(); i++){
            //j++;
            while(j != -1 && s[i] != t[j])
            {
                j = next[j];
            }
            ++j; 
            if(j == t.size()) return i-t.size()+1;
        }
        return -1;
    }
    int strStr(string haystack, string needle) {
        int *next = new int[needle.size()];
        int res=kmp(haystack, needle, next);
        delete []next;
        return res;

    }
};