java 实现 Rabin Karp 字符串查找

题目:实现时间复杂度为 O(n + m)的方法  strStr

strStr 返回目标字串在源字串中第一次出现的第一个字符的位置. 目标字串的长度为 m , 源字串的长度为 n . 如果目标字串不在源字串中则返回 -1。

样例

给出 source = abcdef, target = bcd, 返回 1 .


思路:题目要求时间复杂度为 O(n + m),暴力查找时间复杂度为 O(n^2),不可取。Rabin Karp算法可以满足要求

1.利用hashFunction,对字母进行hash;
2.target字母个数固定,因而target对应的hashcode固定,只需遍历求解source对应的hashcode即可;
3.source每次移动的时候,hashcode要加上后面的字母,同时减去多的那个字母;
4.hashcode相同的时候,不一定代表对应的字母一定相同,需要再次判断; 

5.hashcode:abcde = (a * 31^4 + b * 31^3 +c * 31^2 + d * 31^1 + e * 31^0)% 10^6

6.31为经验值,mod选择的数越大,发生冲突概率越低;

7.mode计算性质,符合结合律,(a+b)% c = a %c + b%c

实现代码如下:

public class Solution {
    /*
     * @param source: A source string
     * @param target: A target string
     * @return: An integer as index
     */
     //10^6
     public int BASE = 1000000;
    public int strStr2(String source, String target) {
      if(source == null || target == null ){
          return -1;
      }
      int m = target.length();
      if(m == 0){
          return 0;
      }
      
      // 31^m 31的m次幂
     int power = 1;
     for(int i = 0; i < m; i++){
         power = power * 31 % BASE;
     }
     //target 的hashcode
     int targetCode = 0;
     for(int i = 0;i < m; i++){
         targetCode = (targetCode * 31 + target.charAt(i)) % BASE;
     }
     
     //soucr hashCode
     int hashCode = 0;
     for(int i = 0; i < source.length(); i++){
         // abc + d
         hashCode = (hashCode * 31 + source.charAt(i)) % BASE;
         if(i < m -1){
             continue;
         }
         
         //abcd - a
         if(i >= m){
             hashCode = hashCode - (source.charAt(i -m) * power) % BASE;
        
         //hashCode < 0单独判断
             if(hashCode < 0 ){
                 hashCode += BASE;
             }
         }
         
         //double check the string
         if(hashCode == targetCode){
             if(source.substring(i - m + 1,i + 1).equals(target)){
                 return i - m + 1;
             }
         }
         
     }
      return -1;
    }
}




  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值