Rabin-Karp字符串匹配算法的滚动哈希

时间:2011-12-12 16:35:11

标签: c# .net data-structures hash rabin-karp

以下是C#...

中Rabin-Karp字符串匹配算法的实现
static void Main(string[] args)
{
  string A = "String that contains a pattern.";
  string B = "pattern";
  ulong siga = 0;
  ulong sigb = 0;
  ulong Q = 100007;
  ulong D = 256;
for (int i = 0; i < B.Length; i++)
{
    siga = (siga * D + (ulong)A[i]) % Q;
    sigb = (sigb * D + (ulong)B[i]) % Q;
}
if (siga == sigb)
{
    Console.WriteLine(string.Format(">>{0}<<{1}", A.Substring(0, B.Length), A.Substring(B.Length)));
    return;
}
ulong pow = 1;
for (int k = 1; k <= B.Length - 1; k++)
    pow = (pow * D) % Q;

for (int j = 1; j <= A.Length - B.Length; j++)
{
    siga = (siga + Q - pow * (ulong)A[j - 1] %Q) % Q;
    siga = (siga * D + (ulong)A[j + B.Length - 1]) % Q;
    if (siga == sigb)
    {
        if (A.Substring(j, B.Length) == B)
        {
            Console.WriteLine(string.Format("{0}>>{1}<<{2}", A.Substring(0, j), 
                                                             A.Substring(j, B.Length), 
                                                             A.Substring(j +B.Length)));
            return;
        }
    }
}
Console.WriteLine("Not copied!");

}

但如果我更改第二个字符串的位置而不是显示结果未复制但

,则会出现一个问题
 string A = "String that contains a pattern.";
 string B = "pattern";

此处显示未复制

 string A = "String that contains a pattern.";
 string B = "Matches contains a pattern ";

我想检查它是否是第一个字符串的副本或者甚至我不会在其中添加内容或更改位置但它不应该有所不同所以如何更改它只是比较每个单词的哈希值在字符串中比实现它............

1 个答案:

答案 0 :(得分:0)

更改

string B = "Matches contains a pattern ";

string B = "contains a pattern ";

它会起作用