public class Solution {
public int BASE = 1000000;
/**
* @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;
int m = target.length();
if(m == 0) return 0;
int power = 1;
int tCode = 0;
for(int i = 0; i < m; i++ ){
power = (power * 33 ) % BASE;
tCode = (tCode * 33 + target.charAt(i)) % BASE;
}
int sCode = 0;
for(int i = 0; i < source.length(); i++){
sCode = (sCode * 33 + source.charAt(i)) % BASE;
if(i < m - 1) continue;
if(i >= m){
sCode = sCode - (source.charAt(i - m) * power) % BASE;
if(sCode < 0) sCode = sCode + BASE;
}
if(tCode == sCode){
if(source.substring(i - m + 1, i + 1).equals(target)){
return i - m + 1;
}
}
}
return -1;
}
}
算法训练:字符串查找(Rabin Karp)
最新推荐文章于 2024-07-20 09:51:47 发布