我一直在尝试理解算法类的 Rabin-Karp 算法。我在理解它时遇到了很多麻烦,所以我尝试实现它(我实际上不必实现它)。我想我正确理解了除了滚动哈希函数之外的所有内容。我的算法目前仅在模式 char[] 与文本 char[] 的开头匹配时才有效。我无法弄清楚我的滚动哈希哪里出错了。如果有人可以请指出错误的方向,我会非常感激。
结果文本“我的测试字符串”模式“我的” - 这作为匹配模式“测试” - 这表明不匹配
private static int int_mod(int a, int b)
{
return (a%b +b)%b;
}
public static int rabin_Karp(char[] text, char[] pattern)
{
int textSize = text.length;
int patternSize = pattern.length;
int base = 257;
int primeMod = 1000000007;
if(textSize < patternSize)
return -1;n
int patternHash = 0;
for(int i = 0; i < patternSize; i++)
patternHash += int_mod(patternHash * base + pattern[i], primeMod);//This is only done once so put method here
System.out.println("patternHash: " + patternHash);
//calculate the value of the first hash
int segmentHash = 0;
for(int i = 0; i < patternSize; i++) //remove this, this will be duplicate
segmentHash += int_mod(segmentHash * base + text[i], primeMod);
System.out.println("segmentHash: " + segmentHash);
Boolean firstMatch = false;
if(segmentHash == patternHash)
{
firstMatch = true;
for(int i=0; i<pattern.length; i++)
{
if(pattern[i] != text[i])
firstMatch = false;
}
}
if (firstMatch == true)
{
return 0;
}
for(int i=1; i<textSize - patternSize; i++)
{
segmentHash += int_mod(segmentHash * base + text[i + pattern.length -1],primeMod);
segmentHash -= int_mod(segmentHash * base + text[i-1], primeMod);
System.out.println("segmentHash: " + segmentHash);
if(segmentHash == patternHash)
{
firstMatch = true;
for(int j=0; j<pattern.length; j++)
{
if(pattern[j] != text[j])
firstMatch = false;
}
}
if (firstMatch == true)
{
return i;
}
}
return -1;
}