模式匹配器获取 ArrayIndexOutOfBoundsException: 0

Pattern Matcher gets ArrayIndexOutOfBoundsException: 0

这是我正在尝试做的伪代码:

procedure naive(T, P):
result = { }
for s = 0 to n – m
    match = true
    for j = 0 to m – 1
        if T[s+j] ≠ P[j]
            match = false
    if match
        result = result + {s}

这是我写的:

public class naivepatternmatcher {
    public static Integer[] main(char[] T, char[] P) {
        Integer[] results = {};
        int count = 0;
        boolean match;
        for (int s = 0; s <= (T.length - P.length); s++) {
            match = true;
            for (int j = 0; j <= P.length - 1; j++) {
                if (T[s + j] != P[j]) {
                    match = false;
                }
            }
            if (match == true) {
                results[count] = s;
                count++;
            }
        }
        return results;
    }
}

当我尝试 运行 我的 Junit 测试时 class 我得到一个 ArrayIndexOutOfBoundsException: 0 at "results[count] = s;" 在我的 main 和 "Integer[] results = naivepatternmatcher.main(Sequence, Pattern1);" 在我的 Junit 测试。

public class naivepatternmatcherTest {

private static final char[] Sequence = new char[] { 'a', 'b', 'a', 'a', 'a',
        'b', 'a', 'c', 'c', 'c', 'a', 'a', 'b', 'b', 'a', 'c', 'c', 'a', 'a',
        'b', 'a', 'b', 'a', 'c', 'a', 'a', 'b', 'a', 'b', 'a', 'a', 'c' };

@Test
public void test() {
    char[] Pattern1 = new char[] { 'a', 'a', 'b' };
    Integer[] ShouldEqual = new Integer[] { 3, 10, 17, 24 };
    Integer[] results = naivepatternmatcher.main(Sequence, Pattern1);
    assertArrayEquals(ShouldEqual, results);
}
}

任何人都可以解决这个问题并解释我缺少什么吗?

您的 results 是一个固定大小为 0 的空数组,results[count] = s 不会将数组的大小增加 1 并向其附加 s 的值。对于这种动态增长的结果,最好使用 ArrayList

另一个建议是在内部 for 循环的 if 末尾添加对 break 的调用,因为如果 T[s + j] != P[j] 则无需进一步搜索模式的其余部分。

if (T[s + j] != P[j]) {
    match = false;
    break
}

请参阅以下代码以获取保持返回类型 Integer[] 且仅在内部使用 ArrayList.

的实现示例
public static Integer[] main(char[] T, char[] P) {
    List<Integer> results = new ArrayList<>();
    boolean match;
    for (int s = 0; s <= (T.length - P.length); s++) {
        match = true;
        for (int j = 0; j <= P.length - 1; j++) {
            if (T[s + j] != P[j]) {
                match = false;
                break;
            }
        }
        if (match == true) {
            results.add(s);
        }
    }
    return results.toArray(new Integer[results.size()]);
}

See it run live