10、实现 strStr()
思路一:朴素模式匹配算法
最朴素的方法就是依次从待匹配串的每一个位置开始,逐一与模版串匹配,
因为最多检查 (n - m)个位置,所以方法的复杂度为 O(m*(n-1))。
<div align="center"><img src="https://github.com/DuHouAn/ImagePro/raw/master/java-notes/leetcode/string/str_1.png" width="500"/></div>
//haystack 是待匹配串
//needle 是模板串
public int strStr(String haystack, String needle) {
if(needle==null || needle.length()==0){
return 0;
}
int i=0,j=0;
//k存储的是模板串在待匹配串的位置
int k=i;
while(i<haystack.length() && j<needle.length()){
if(haystack.charAt(i)==needle.charAt(j)){
i++;
j++;
}else{
j=0;
i=++k;
}
}
//说明模板串是待匹配串的子串
if(j==needle.length()){
return k;
}
return -1;
}
思路二:基于朴素模式匹配算法改进,即 KMP算法
1.求next数组
private int[] getNext(String needle) {
int[] next=new int[needle.length()];
int j=0,t=-1;
next[0]=-1;
while (j<needle.length()-1){
if(t==-1 || needle.charAt(j)==needle.charAt(t)){
//needle.charAt(j): 表示后缀的单个字符
//needle.charAt(t): 表示前缀的单个字符
next[j+1]=t+1;
t++;
j++;
}else{
t=next[t];
}
}
return next;
}
next[j]的值(也就是t)表示,当P[j] != T[i]时,j指针的下一步要移动到的位置(其中P是模式串,T是主串)。
当P[k] == P[j]时,有next[j+1] == next[j] + 1
当P[k] != P[j]时,则循环将k赋值给next[k],一直到k=-1为止。初始时next[0]=-1。
public int strStr(String haystack, String needle) {
if(needle==null || needle.length()==0){
return 0;
}
int[] next=getNext(needle);
int i=0,j=0;
while(i<haystack.length() && j<needle.length()){
if(j==-1 || haystack.charAt(i)==needle.charAt(j)){
i++;
j++;
}else{
j=next[j];
}
}
//说明模板串是待匹配串的子串
if(j==needle.length()){
//返回的是待匹配串的下标
return i-needle.length();
}
return -1;
}
private int[] getNext(String needle) {
int[] next=new int[needle.length()];
next[0]=-1;
int j=0,t=-1;
while (j<needle.length()-1){
if(t==-1 || needle.charAt(j)==needle.charAt(t)){
next[j+1]=t+1;
t++;
j++;
}else{
t=next[t];
}
}
return next;
}
https://www.mianshi.online,[https://www.i9code.cn](
本文由博客一文多发平台 OpenWrite 发布!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。