[Leetcode]28. Implement strStr()

版权声明:转载请联系博主 https://blog.csdn.net/zxtalentwolf/article/details/84405504

题目很简单,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;

    }
};

猜你喜欢

转载自blog.csdn.net/zxtalentwolf/article/details/84405504