Knuth–Morris–Pratt 字符串匹配
public class Solution {
public int strStr(String haystack, String needle) {
if(haystack.length() < needle.length()) return -1;
if(needle.length() == 0) return 0;
int[] next = getNext(needle);
int q = 0; // number of chars matched in pattern
for(int i = 0; i < haystack.length(); i++){
while(q > 0 && needle.charAt(q) != haystack.charAt(i)){
q = next[q - 1];
}
if(needle.charAt(q) == haystack.charAt(i)){
q ++;
}
if(q == needle.length()){
return i - needle.length() + 1;
}
}
return -1;
}
private int[] getNext(String pattern){
int M = pattern.length();
int[] next = new int[M];
int k = 0; // number of chars matched in pattern
for(int i = 1; i < M; i++){
while(k > 0 && pattern.charAt(k) != pattern.charAt(i)){
k = next[k - 1];
}
if(pattern.charAt(k) == pattern.charAt(i)){
k ++;
}
next[i] = k;
}
return next;
}
}next[] 里的 k = 正确 match 的长度
next[] 中,每个位置的数字是由 k 赋值的,代表“如果下一个字符串挂了,在我这个位置截止的字符串正确 match 的长度是多少”
match 函数的逻辑基本和 getNext 完全一样,k 代表目前的 text 上 match pattern 的字符串长度。
给两个字符串,找到第二个在第一个中第一次出现的位置(自己写string.indexOf这个函数吧),followup1,找一个字符串中period的字符段,followup2,找到period次数最少的,例如abababab,ab出现了4次,abab出现了2次,返回2
Last updated