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;
}
}