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
.
每进行一次hash运算的时候,都需要进行取模处理;
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 (source == null || target == null) {
return -1;
}
if (target.length() == 0) {
return 0;
}
int sourceLen = source.length();
int targetLen = target.length();
int sourceVal = 0;
int targetVal = 0;
int BASE = 10000;
int magic = 33;
int val = 1;
for (int i = 0; i < targetLen; i++) {
targetVal = targetVal * magic + target.charAt(i) - 'a';
targetVal %= BASE;
}
for (int i = 0; i < targetLen - 1; i++) {
val *= magic;
val %= BASE;
}
for (int i = 0; i < sourceLen; i++) {
if (i >= targetLen) {
sourceVal -= (source.charAt(i - targetLen) - 'a') * val;
sourceVal %= BASE;
if (sourceVal < 0) {
sourceVal += BASE;
}
}
sourceVal = sourceVal * magic + source.charAt(i) - 'a';
if (i >= targetLen - 1 && sourceVal == targetVal) {
if (target.equals(source.substring(i - targetLen + 1, i + 1))) {
return i - targetLen + 1;
}
}
}
return -1;
}
}