LeetCode strStr java solution (use rabin karp)

题目要求:
Implement strStr function in O(n + m) time.

strStr return the first index of the target string in a source string. The length of the target string is m and the length of the source string is n.
If target does not exist in source, just return -1.

Given source = abcdef, target = bcd, return 1.

使用算法实现 O(m + n)的时间复杂度

正常情况之下, 网上有非常多的教程要求大家使用KMP算法将暴力循环的方式得时间复杂度降低到O(m+n),但是KMP方法非常复杂并且难以理解,因为有些时候你根本不明白为什么要使用这样的方式来进行处理,但是使用 robin karp方法就非常友好, robin karp方法使用的是基于Hash Function的方式来降低时间复杂度.使用karp算法的时候,一定要注意中间的多次取摸运算.

public class Solution {
    /**
     * @param source a source string
     * @param target a target string
     * @return an integer as index
     */
    private int BASE = 1000000;
    public int strStr2(String source, String target) {
        // Write your code here
        if (source == null || target == null) {
            return -1;
        }
        if (source.length() == 0 && target.length() != 0) {
            return -1;
        }
        if (target.length() == 0) {
            return 0;
        }
        int soulen = source.length();
        int tarlen = target.length();
        int tarHash = 0;
        int souHash = 0;
        int value = 1;
        for (int i = 0; i < tarlen; i++) {
            tarHash = (tarHash * 31 + target.charAt(i) - 'a') % BASE;
        }
        for (int i = 0; i < tarlen - 1; i++) {
            value *= 31;
            value %= BASE;
        }
        for (int i = 0; i < soulen; i++) {
            if (i >= tarlen) {
                souHash = (souHash - (source.charAt(i - tarlen) - 'a') * value) % BASE;
                if (souHash < 0) {
                    souHash += BASE;
                }
            }
            souHash = (souHash * 31 + source.charAt(i) - 'a') % BASE;
            if (i >= tarlen - 1 && tarHash == souHash) {
                if (source.substring(i - tarlen + 1, i + 1).equals(target)) {
                    return i - tarlen + 1;
                }
            }
        }
        return -1;
    }
}

今天先写到这里, 有些具体的细节等有时间了再进行具体的处理.

updata, 今天发现了一个问题,同样是相同的题目,在lintcode上能够通过,但是在leetcode上面是不能通过的,leetcode上面的测试样例要更多一些.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ncst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值