将一个String转成相应的哈希值,假设string s的长度是m, 通过Rabin Karp算法,得到s[0...m - 1]的值为 s[0] * Base ^ (m - 1) + s[1] * Base ^ (m -2) + .... + s[m - 2] * Base ^ 1 + s[m - 1] * Base ^ 0
// 以Strstr()为例
public int strStr(String haystack, String needle) {
// Rabin Karp Algorithm
if (haystack.length() < needle.length()) {
return -1;
}
String t = haystack;
String s = needle;
int BASE = 256;
// Avoid overflow
long sHash = 0, tHash = 0;
long powerS = 1;
for (int i = 0; i < s.length(); i++) {
tHash = tHash * BASE + t.charAt(i);
sHash = sHash * BASE + s.charAt(i);
powerS *= BASE;
}
// powerS == BASE ^ (s.length() - 1)
powerS /= BASE;
for (int i = s.length(); i < t.length(); i++) {
if (tHash == sHash && t.substring(i - s.length(), i).equals(s)) {
return i - s.length();
}
tHash -= t.charAt(i - s.length()) * powerS;
tHash = tHash * BASE + t.charAt(i);
}
if (tHash == sHash && t.substring(t.length() - s.length()).equals(s)) {
return t.length() - s.length();
}
return -1;
}
3. Time & Space Complexity