594.strStr II

描述

实现时间复杂度为 O(n + m)的方法 strStr。
strStr 返回目标字串在源字串中第一次出现的第一个字符的位置. 目标字串的长度为 m , 源字串的长度为 n . 如果目标字串不在源字串中则返回 -1。

样例

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

知识点:

Rabin-Karp algorithm:
使用哈希函数使得字符串的比较变成整数的比较,O(1) 的时间得到字符串对应的 hashcode,保证从 key 到 value 是唯一的就可以了(从 value 到 key 不一定唯一)

此算法主要练习 hashfunction 写法

代码

public class Solution {
    public int BASE = 10000000;
    /**
     * @param source a source string
     * @param target a target string
     * @return an integer as index
     */
    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,取模是为了将数控制在一定范围
        int power = 1;
        for (int i = 0; i < m; i++) {
            // 不一定要乘以 31;其他数也可以
            power = (power * 31) % BASE;
        }
        
        // targetcode
        int targetcode = 0;
        for (int i = 0; i < m; i++) {
            // hashcode, abc + d;
            // int 类型 + char 类型,会将 char 类型强制转换为 int 类型
            targetcode = (targetcode * 31 + target.charAt(i)) % BASE;
        }
        
       
        int hashcode = 0;
        // 注意 for 循环的起始值是从 0 开始的
        for (int i = 0; i < source.length(); i++) {
            hashcode = (hashcode * 31 + source.charAt(i)) % BASE;
        
            // hashcode
            // abcd - a (由于有后面的 if 条件句,hashcode 计算
            // 不会超过 target.length() + 1 个字符)
            // if 只负责不符合要求的异常情况,等于 m-1 正是我们想要的,不用理会
            if (i < m - 1) {
                continue;
            }
            if (i >= m) {
                hashcode = hashcode - (source.charAt(i - m) * power) % BASE;
            }
            if (hashcode < 0) {
                hashcode += BASE;
            }
            if (hashcode == targetcode) {
                if (source.substring(i - m + 1, i + 1).equals(target)) {
                    return i - m + 1;
                }
            }
        }
        return -1;
    }
}

你可能感兴趣的:(594.strStr II)