strStr II

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.

Example

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

使用HashFunction的方式来取代KMP算法,时间复杂度与KMP算法相同,是O(n)
java
public class Solution {
    /*
     * @param source: A source string
     * @param target: A target string
     * @return: An integer as index
     */
    public int strStr2(String source, String target) {
        // write your code here
        if (target == null || source == null) {
            return -1;
        }
        if (target.length() == 0 && source != null) {
            return 0;
        }
        int sourceLen = source.length();
        int targetLen = target.length();
        int sourceVal = 0;
        int targetVal = 0;
        int val = 1;
        int BASE = 10000;
        for (int i = 0; i < targetLen; i++) {
            targetVal = targetVal * 33 + target.charAt(i) - 'a';
            targetVal %= BASE;
        }
        for (int i = 0; i < targetLen - 1; i++) {
            val *= 33;
            val %= BASE;
        }
        for (int i = 0; i < sourceLen; i++) {
            if (i >= targetLen) {
                sourceVal = (sourceVal - (source.charAt(i - targetLen) - 'a') * val) % BASE;
                if (sourceVal < 0) {
                    sourceVal += BASE;
                }
            }
            sourceVal = (sourceVal * 33 + source.charAt(i) - 'a') % BASE;
            if (i >= targetLen - 1 && sourceVal == targetVal) {
                if (source.substring(i - targetLen + 1, i + 1).equals(target)) {
                    return i - targetLen + 1;
                }
            }
        }
        return -1;
    }
}


  • 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、付费专栏及课程。

余额充值