码迷,mamicode.com
首页 > 其他好文 > 详细

28. Implement strStr()

时间:2017-07-19 20:36:49      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:stack   abi   bsp   typedef   returns   turn   type   log   复杂度   

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()

标签:stack   abi   bsp   typedef   returns   turn   type   log   复杂度   

原文地址:http://www.cnblogs.com/pk28/p/7207550.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!