0

こんにちは、Algorithms in C book からKMP 検索の C# バージョンを作成しようとしています。アルゴリズムの欠陥を見つけるのに苦労しています。誰か助けてくれる?

static int KMP(string p, string str) {
    int m = p.Length;
    int n = str.Length;
    int i;
    int j;

    int[] next = new int[m];
    next[0] = -1;

    for (i = 0, j = -1; i < m; i++, j++, next[i] = j) { 
                                        //Getting index out of bounds
        while (j > 0 && p[i] != p[j]) j = next[j];
    }

    for (i = 0, j = 0; i < n && j < m; i++, j++) {
        while (j >= 0 && p[j] != str[i]) j = next[j];
        if (j == m) return i - m;
    }

    return -1;
}
4

1 に答える 1

1

簡単な答えは、最初のループで i++ が next[i] = j の前に解決されるため、検索文字列の最後の文字で next[m+1] を j に設定しようとすることです。これにより、範囲外のインデックス例外が発生します。順序を変更してみてください:

for (i = 0, j = -1; i < m;  next[i] = j, i++, j++)

より根本的には、実装をテスト可能な部分に分割してみてください。たとえば、最初のループが検索語の計算テーブルを構築しているため、テスト可能なメソッドを抽出できます。皮切りに:

public int[] BuildTable(string word)
{
    // todo
}

ウィキの説明に基づくいくつかのNUnit テスト

[Test]
public void Should_get_computed_table_0_0_0_0_1_2_given_ABCDABD()
{
    const string input = "ABCDABD";
    var result = BuildTable(input);
    result.Length.ShouldBeEqualTo(input.Length);
    result[0].ShouldBeEqualTo(-1);
    result[1].ShouldBeEqualTo(0);
    result[2].ShouldBeEqualTo(0);
    result[3].ShouldBeEqualTo(0);
    result[4].ShouldBeEqualTo(0);
    result[5].ShouldBeEqualTo(1);
    result[6].ShouldBeEqualTo(2);
}

[Test]
public void Should_get_computed_table_0_1_2_3_4_5_given_AAAAAAA()
{
    const string input = "AAAAAAA";
    var result = BuildTable(input);
    result.Length.ShouldBeEqualTo(input.Length);
    result[0].ShouldBeEqualTo(-1);
    result[1].ShouldBeEqualTo(0);
    result[2].ShouldBeEqualTo(1);
    result[3].ShouldBeEqualTo(2);
    result[4].ShouldBeEqualTo(3);
    result[5].ShouldBeEqualTo(4);
    result[6].ShouldBeEqualTo(5);
}

次に、KMP メソッドのテストを 1 つ以上作成します。

[Test]
public void Should_get_15_given_text_ABC_ABCDAB_ABCDABCDABDE_and_word_ABCDABD()
{
    const string text = "ABC ABCDAB ABCDABCDABDE";
    const string word = "ABCDABD";
    int location = KMP(word, text);
    location.ShouldBeEqualTo(15);
}

次に、ウィキのアルゴリズムの説明で使用されている構造を使用して実装すると、それがまとまるはずです。

public int KMP(string word, string textToBeSearched)
{
    var table = BuildTable(word);
    // rest of algorithm
}
于 2010-10-14T19:55:22.817 に答える