0
点赞
收藏
分享

微信扫一扫

[力扣][C++]28. 实现 strStr()

class Solution {
    int ne[50000 + 10];
public:
    int strStr(string haystack, string needle) {
        if(needle.length() == 0) return 0;
        ne[0] = -1;
        for(int i = 1,j = -1;i < needle.length();i++){
            while(j != -1 && needle[i] != needle[j + 1]) j = ne[j];
            if(needle[i] == needle[j + 1]) j ++;
            ne[i] = j;
        }

        for(int i = 0,j = -1;i < haystack.length();i++){
            while(j != -1 && haystack[i] != needle[j + 1]) j = ne[j];
            if(haystack[i] == needle[j + 1]) j++;
            if(j == needle.length() - 1) return i - j;
        }
        return -1;
    }
};

因为本题字符串长度较大, 0 < = h a y s t a c k . l e n g t h , n e e d l e . l e n g t h < = 5 ∗ 104 0 <= haystack.length, needle.length <= 5 * 104 0<=haystack.length,needle.length<=5104,所以不宜采用BF算法进行匹配,而应该考虑采用KMP算法。


题目链接
原创不易,感谢支持!

举报

相关推荐

0 条评论