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.

題意&解題思路

如題,直接用KMP算法解決,代碼如下:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int l1 = needle.length();
        if(l1 == 0)return 0;
        int* Next = new int[l1];
        Next[0] = 0;
        for(int i = 1, l = 0; i < l1;){
            if(needle[i] == needle[l])Next[i++] = ++l;
            else if(l)l = Next[l - 1];
            else Next[i++] = 0;
        }
        int len = haystack.length();
        for(int i = 0, j = 0; i < len;){
            if(haystack[i] == needle[j]){
                i++;j++;
            }
            else{
                if(j)j = Next[j - 1];
                else i++;
            }
            if(j == l1)return i - j;

        }
        return -1;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章