题目:实现时间复杂度为 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;
}
}