LintCode 594: strStr II (Rabin Karp算法)

Solution是基于Rabin Karp算法,参考了九章的内容。
Rabin Karp算法用hash function来算出source 和 target的hash code来比较,从而将时间复杂度从O(n^2)降到O(n)。
该算法的关键在于计算source的hash code的过程中,采用循环移位来计算。
例如,
source = “abcde”, target = “cd”.

计算source的hash code的过程中,依次计算每2位(因为target长度为2)的hash code值。
hashcode(cd) = (hashcode(bc + d) - hashcode(b)*2 ) % BASE

如果hashcode值为负,则 hashcode += BASE.

class Solution {
public:
    /*
     * @param source: A source string
     * @param target: A target string
     * @return: An integer as index
     */
    int strStr2(const char* source, const char* target) {
        if (!source || !target) return -1;
        if (strlen(source) == 0 && strlen(target) == 0) return 0;
        if (strlen(source) && !strlen(target)) return 0;
        
        int lenS = strlen(source);
        int lenT = strlen(target);
        int BASE = 1e+6;
        
        if (lenS < lenT) return -1;
        
        int power31_lenT= 1;   // 31^lenT
        for (int i = 0; i < lenT; ++i) {
            power31_lenT = (power31_lenT * 31) % BASE;
        }
        
        int hashTgt = 0;
        for (int i = 0; i < lenT; ++i) {
            hashTgt = (hashTgt * 31 + target[i]) % BASE;
        }
        
        int hashSrc = 0;
        for (int i = 0; i < lenS; ++i) {
            
            hashSrc = (hashSrc * 31 + source[i]) % BASE;
            if (i < lenT) continue;
            
            // abcd - a
            hashSrc -= (source[i - lenT] * power31_lenT) % BASE;
            if (hashSrc < 0) 
                hashSrc += BASE;
            
            if (hashSrc == hashTgt) {
                for (int j = 0; j < lenT; ++j) {
                    if (source[i - lenT  + 1 + j] != target[j]) return -1;
                }
                return i - lenT + 1;
            }
        }
        
        return -1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值