594.strStr II
1.Description(Hard)
2.Code
public int strStr2(String source, String target) {
// Write your code here
if (source == null || target == null) {
return -1;
}
int N = source.length();
int M = target.length();
if (M == 0) {
return 0;
}
int R = 31;
int Q = 997;
int RM = 1;
for (int i = 0; i < M; i++) {
RM = RM * R % Q;
}
int targetHash = 0;
for (int i = 0; i < M; i++) {
targetHash = (targetHash * R + target.charAt(i)) % Q;
}
int sourceHash = 0;
for (int i = 0; i < N; i++) {
sourceHash = (sourceHash * R + source.charAt(i)) % Q;
if (i < M - 1) {
continue;
}
if (i >= M) {
sourceHash = sourceHash - (source.charAt(i - M) * RM) % Q;
if (sourceHash < 0) {
sourceHash += Q;
}
}
if (sourceHash == targetHash) {
if (source.substring(i - M + 1, i + 1).equals(target)) {
return i - M + 1;
}
}
}
return -1;
}Last updated