28. Implement strStr()

Posted いいえ敗者

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

 

 

字符串Rabin--Karp算法。滚动哈希,时间复杂度o(n+m),觉得比kmp好写

class Solution {
public:
    const unsigned long long T = 100000007;
    int strStr(string haystack, string needle) {
        typedef unsigned long long ull;
        int al = needle.length();
        int bl = haystack.length();
        if (al > bl) return -1;
        ull A = 0;
        ull B = 0;
        ull t = 1;
        for (int i = 0; i < al; ++i) {
            A = A * T + needle[i];
            B = B * T + haystack[i];
            t *= T;
        }
        //cout << A << " "<<B<<endl;
        for (int i = 0; i + al <= bl; ++i) {
            if (A == B) return i;
            if (i + al < bl) B = B * T - t * haystack[i] + haystack[i + al];
        }
        return -1;
    }
};

 

以上是关于28. Implement strStr()的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 28. Implement strStr() 实现strStr()

28. Implement strStr()

28. Implement strStr()

[LeetCode] 28. Implement strStr() 实现strStr()函数

28. Implement strStr()

28. Implement strStr()(js)