题目要求:
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.
Given source = abcdef, target = bcd, return 1.
使用算法实现 O(m + n)的时间复杂度
正常情况之下, 网上有非常多的教程要求大家使用KMP算法将暴力循环的方式得时间复杂度降低到O(m+n),但是KMP方法非常复杂并且难以理解,因为有些时候你根本不明白为什么要使用这样的方式来进行处理,但是使用 robin karp方法就非常友好, robin karp方法使用的是基于Hash Function的方式来降低时间复杂度.使用karp算法的时候,一定要注意中间的多次取摸运算.
public class Solution {
/**
* @param source a source string
* @param target a target string
* @return an integer as index
*/
private int BASE = 1000000;
public int strStr2(String source, String target) {
// Write your code here
if (source == null || target == null) {
return -1;
}
if (source.length() == 0 && target.length() != 0) {
return -1;
}
if (target.length() == 0) {
return 0;
}
int soulen = source.length();
int tarlen = target.length();
int tarHash = 0;
int souHash = 0;
int value = 1;
for (int i = 0; i < tarlen; i++) {
tarHash = (tarHash * 31 + target.charAt(i) - 'a') % BASE;
}
for (int i = 0; i < tarlen - 1; i++) {
value *= 31;
value %= BASE;
}
for (int i = 0; i < soulen; i++) {
if (i >= tarlen) {
souHash = (souHash - (source.charAt(i - tarlen) - 'a') * value) % BASE;
if (souHash < 0) {
souHash += BASE;
}
}
souHash = (souHash * 31 + source.charAt(i) - 'a') % BASE;
if (i >= tarlen - 1 && tarHash == souHash) {
if (source.substring(i - tarlen + 1, i + 1).equals(target)) {
return i - tarlen + 1;
}
}
}
return -1;
}
}
今天先写到这里, 有些具体的细节等有时间了再进行具体的处理.
updata, 今天发现了一个问题,同样是相同的题目,在lintcode上能够通过,但是在leetcode上面是不能通过的,leetcode上面的测试样例要更多一些.