了解KMP解决方案-蛮力

时间:2018-10-02 13:46:17

标签: java algorithm data-structures

嗨,我正在尝试通过蛮力理解KMP解决方案。我在leetcode上找到了解决方案。

public static int strStr(String haystack, String needle) {
    if (needle == null || needle.length() < 1) {
        return 0;
    }

    for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
        if (isValid(haystack, needle, i)) {
            return i;
        }
    }
    return -1;
}

public static boolean isValid(String haystack, String needle, int index) {
    for (int i = 0; i < needle.length(); i++) {
        if (haystack.charAt(index + i) != needle.charAt(i)) {
            return false;
        }
    }
    return true;
}

在这里,我们正在做haystack.length() - needle.length() + 1。我不明白为什么在for循环中我们减去干草堆和针长,然后再加1。有人可以帮我理解为什么吗。谢谢。

1 个答案:

答案 0 :(得分:1)

useSuppliedContext: trueneedle的第一个字符不能放在位置haystack之后,因为没有足够的字符可匹配。函数haystack.length - needle.length - 1甚至会超出范围,因为不会为所有isValid都定义haystack.charAt(index + i)

相关问题