leetcode #28 in cpp

This one is to find a pattern string in a text string. Most of solutions use std::find() but I would rather write my own. So I implement this function using Rabin-Karp algorithm. Another method could be Knuth-Morris-Pratt. In general Rabin-Karp algorithm is more understandable and easier to implement. 

Solution: 

Rabin-Karp Algorithm is a comparison method using Hashing. Given a base( say in human-maths the base is 10) and a prime, the hash value of a string is :

hval = ( str[0] *base^(d-1) + str[1] * base^(d-2) + ....... str[d]*1 ) mod prime, if the length of the string is d; ------Eqn. 1.

This is similar to how we computer a number. Say 100 = 1 * 10^(3-1) + 0 * 10^(3-2) + 0*1. Usually the base is choses as 256 for string character and 101 could be used as the prime.

Here is how it works with the hash function: 

        Given a pattern string and a text string, if the hash value of the pattern == hash value of any text substring of the same length, then we check character to character if the the substring is the pattern substring. If not, then we skip to the next substring. 

So each time we get a substring of the text, by scanning through the text and get a substring of the pattern's length, we need to get the hash value of the text substring. But if we directly compute the hash value of the substring, it makes no sense to use this method instead of brute force.  Thus the most important  thing in Rabin-Karp algorithm is how to speed up getting a hash value. An example is as follows:

Say we have 'abcd' as the text string, and the substring length should be 3. 

Denote the multiplier (base^(3-1)) as high_mul for the leftmost character in the substring.

First we could compute hash('abc') = ( 'a' * high_mul + 'b' * base^(1) + 'c' ) mod prime.

Then hash('bcd') =( ( hash('abc') - 'a' * high_mul ) * base + 'd' ) mod prime; 

This key step generates a new hash value for the new substring by subtracting one old character and adding one new character. This speeds up the algorithm a lot.

Code: 

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(haystack.empty()&&needle.empty()) return 0;
        if(haystack.size() < needle.size()) return -1;
        int q = 101;
        return rabin_karp(haystack, needle,q);
    }
    
    int rabin_karp(string txt, string pattern,int q){
        int plen = pattern.length();
        int tlen = txt.length();
        int base = 256;
        
        int phash = 0;//hashval for pattern string
        int thash = 0;//hashval for text substring
        int high_mul = 1;
        int i;
        for(i = 0; i < plen - 1; i++){
            high_mul = (high_mul * base) %q;//compute highest multiplier
        }
        for(i = 0; i < plen; i ++){
            phash = (phash*base+ pattern[i]) % q;//compute hashval for pattern
            thash = (thash*base + txt[i]) % q;//computer hashval for the first substring in the text
        }

        i = 0;
        int find;
        while(i<=tlen - plen){
            
            if(phash == thash){// if hashvals are equal, check character by character if they are the same.
                
                find = 1;
                for(int j = i; j < i + plen; j ++){
                    if(pattern[j-i] != txt[j]){
                        find = 0;
                        break;
                    }
                }
                if(find) return i;
            }else{ //if not the same, go to the next substring
                if(i > tlen- plen) return -1;
                thash = ((thash - high_mul*txt[i]) * base + txt[i + plen]) % q;//key step
                if(thash < 0) thash += q;// this is important. we might get negative numbers when hashing. make it positive.
            }
        
            i++;   
        }
        
        
        return -1;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值