Java 了解KMP解决方案-蛮力
嗨,我想通过暴力来理解KMP的解决方案。我在leetcode找到了解决方案Java 了解KMP解决方案-蛮力,java,algorithm,data-structures,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++) {
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;
}
public static int strStr(字符串草垛、字符串针){
如果(针==null | |针.长度()<1){
返回0;
}
对于(int i=0;i
我们正在做的是
haystack.length()-needle.length()+1
。我不明白为什么在for循环中我们减去干草堆和针的长度,然后再加上1。有人能帮我理解为什么吗。谢谢。haystack中针的第一个字符不能位于positionhaystack.length-pinder.length-1
之后,因为没有足够的字符匹配。函数isValid
甚至会抛出一个数组索引,因为不会为所有0定义haystack.charAt(index+i)