28. 找出字符串中第一个匹配项的下标 - 力扣(LeetCode)
KMP算法
内容:
该算法为了解决对字符串匹配问题求解
查找在一个字符串中 是否包含另外一个字符串,
我们把第一个字符串称为主串,第二个称为模式串
常规思路(暴力解法):
用两层for循环来暴力求解,时间复杂度用时O(n*m) 即为二者长度的乘积
代码如下:
class Solution {
public int strStr(String haystack, String needle) {
if(haystack.length() < needle.length()) return -1;
int index = -1;
int j = 0;
for(int i = 0 ; i < haystack.length() ; i++) {
if(haystack.charAt(i) == needle.charAt(j)) {
index = i;
while(j<needle.length()) {
//第二层for
if(i >= haystack.length()) {
return -1;
}
if(haystack.charAt(i) != needle.charAt(j)) {
i = index;
j = 0;
index = -1;
break;
}
i++;
j++;
}
if(index != -1) return index;
}
}
return index;
}
}
这样的解法没什么问题,但是很费事,如果一旦二者字符串长度增大,效率就会变得很低.
KMP算法
既然N^2级别的时间效率较低,我们是否可以想办法降低时间达到O(nlogn)级别,甚至是到O(n)级别呢.
KMP算法就是三位大神所研究的, O(N)级的时间复杂度的算法.
但是在正式进入KMP之前