暴力破解:
字符串A,字符串B,从A里找B。
从A的第一个开始跟B匹配,直到不匹配,从A的第二个开始匹配.....直到A无了。
需要两个指针。
时间复杂度n*n
public static int strStr(String haystack, String needle) {
//BF算法(Brute Force)
int n =haystack.length();
int m = needle.length();
for (int i = 0;i<=n-m;i++){
boolean flag = true;
for (int j =0;j<m;j++ ){
if (haystack.charAt(i+j)!=needle.charAt(j)){
flag = false;
break;
}
}
if(flag==true){
return i;
}
}
return -1;
}
KMP
// KMP算法(Knuth-Morris-Pratt)
int n = haystack.length(), m = needle.length();
if (m == 0) {
return 0;
}
int[] next = new int[m];//为数组pi分配了m spaces
//构造next数组
//i指针一直后移 与j对比
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
j = next[j - 1];
//如果不相等,就让j到next数组的前一个位置
//(想不明白为啥,但是又很正确很神奇!)
}
if (needle.charAt(i) == needle.charAt(j)) {
j++;//如果相等,说明前后缀一样 +1
}
//i这个位置的值为j
next[i] = j;
}
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
j = next[j - 1];
}
if (haystack.charAt(i) == needle.charAt(j)) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
这个算法看的我头大,找到最长的相等的前后缀,可以不用顺着A的顺序一个一个比了
首先要构造next数组,就是比到目前,符合的前后缀的数量(只跟B字符串有关,与A无关)。构造好之后,在比的时候如果不匹配了,根据这个数组返回到相应的位置再比。
时间复杂度n*m。
力扣 题解宫水三叶讲的好好!!!