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

Implement strStr() -- leetcode

时间:2014-12-30 11:51:42      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:leetcode   面试   strstr   rabin   karp   

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button to reset your code definition.



算法一,Brute force


算法二,Rabin–Karp algorithm

特点是采取Rolling hash

先计算好待查字符串needle的Hash值。然后将被搜索字符串haystack逻辑上分成若干组,每组长度与needle长度相同。每组分别计算Hash值。这样,比较字符串,变成了比较了比较Hash值。

所谓Rolling Hash,就是后一组的Hash计算,可以利用前一组的Hash成果。

因为后一组字符的组成与前一组的关系为,吐出尾部字符,吸纳一个新字符。这样计算Hash时,也回滚掉吐出的字符,吸纳进新的字符。


该算法在leetcode上实际执行时间为40ms。

class Solution {
public:
    int strStr(char *haystack, char *needle) {
        const int q = 3355439;
        const int r = 256;

        int nLen = 0;
        int nHash = 0;
        int weight = 1;
        while (*needle) {
                nHash = ((nHash * r) % q + *needle) % q;
                weight = nLen ? (weight * r) % q : 1;
                ++needle;
                ++nLen;
        }

        if (!nLen) return 0;

        int k = nLen;
        int hHash = 0;
        while (*haystack && k) {
                hHash = ((hHash * r) % q + *haystack) % q;
                ++haystack;
                --k;
        }

        if (k) return -1;
        if (nHash == hHash &&
                !strncmp(haystack-nLen, needle-nLen, nLen))
                return 0;

        int i = 1;
        while (*haystack) {
                hHash = ((hHash - (haystack[-nLen] * weight) % q) % q + q) % q;
                hHash = ((hHash * r) % q + *haystack) % q;
                if (nHash == hHash &&
                        !strncmp(haystack-nLen+1, needle-nLen, nLen))
                        return i;

                ++haystack;
                ++i;
        }

        return -1;
    }
};

参考资料

http://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm

http://en.wikipedia.org/wiki/Rolling_hash

Implement strStr() -- leetcode

标签:leetcode   面试   strstr   rabin   karp   

原文地址:http://blog.csdn.net/elton_xiao/article/details/42262681

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