Description
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
.
Solution
使用算法实现 O(m + n)的时间复杂度。
正常情况之下,网上有非常多的教程要求大家使用KMP算法将暴力循环的方式得时间复杂度降低到O(m+n),但是KMP方法非常复杂并且难以理解,因为有些时候你根本不明白为什么要使用这样的方式来进行处理,但是使用 robin karp方法就非常友好, Rabin Karp方法使用的是基于Hash Function的方式来降低时间复杂度。使用karp算法的时候,一定要注意中间的多次取摸运算。
java
public class Solution {
/*
* @param source: source string to be scanned.
* @param target: target string containing the sequence of characters to match
* @return: a index to the first occurrence of target in source, or -1 if target is not part of source.
*/
public int strStr(String source, String target) {
// write your code here
if (target == null || source == null) {
return -1;
}
//先判断字符串不为空,才能往下计算字符串长度
int targetLen = target.length();
int sourceLen = source.length();
int magic = 33; //magic 可以是任意数字31之类的,只是hash值的计算参数,选33可能效率高一些
if (targetLen == 0 && source != null) { //if之后targetLen != 0
return 0;
}
if (sourceLen == 0) {
return -1;
}
//mode could be any big integer
//just make sure mod * magic won't exceed max value of int.
int mod = Integer.MAX_VALUE / magic; //取模之后可以防止hash计算的过程中超过int的限制。mod取得数字越大,则得到的结果数越多,越容易进行判断是否相等。
//计算target的hash值
int tarHash = 0;
for (int i = 0; i < targetLen; i++) {
tarHash = (tarHash * magic + (target.charAt(i) - 'a')) % mod;
if (tarHash < 0) {
tarHash += mod;
}
}
//计算magic的targetLen次方,方便之后的减去开头字母的hash值
int value = 1;
for (int i = 0; i < targetLen; i++) {
value = value * magic % mod; //边乘边取模,防止超过int
}
//计算source中依次取targetLen个字母的hash值,并与target的hash值进行比较
int souHash = 0;
for (int i = 0; i < sourceLen; i++) {
//将当前的hash值加上下一个字母的hash值
souHash = (souHash * magic + source.charAt(i) - 'a') % mod;
//如果取到targetLen之后,则需要每次再减去多余的首个字母
// i
//abcd - a
if (i >= targetLen) {
souHash = (souHash - (source.charAt(i - targetLen) - 'a') * value) % mod;
}
//防止计算的hash值出现负数
if (souHash < 0) {
souHash += mod;
}
//如果i满足target的长度则需要判断hash是否相等
if (i >= targetLen - 1 && souHash == tarHash) {
//double check the string
//hash值不相等则字符串一定不同,但是hash值相同时字符串不一定相同,需要额外再equals()方法判断一下
if (target.equals(source.substring(i - targetLen + 1, i + 1))) { //substring(起始位置,结束为止) [起始位置,结束位置),左闭右开区间
return i - targetLen + 1;
}
}
}
//循环结束仍未发现相同项,则返回-1
return -1;
}
}