next数组修正版KMP算法
标签:ext nbsp length puts style ack int main arch
public class Kmp {
String snippet;
String searchText;
int[] next;
public Kmp(String inputString) {
this.snippet = inputString;
// next = new int[this.snippet.length()];
}
public void setNext(String searchText){
this.searchText = searchText;
// String copySnippet = searchText;
this.next = new int[searchText.length()];
this.next[0]=-1;
for(int frontIndex=0,backIndex=-1;frontIndex;){
if(backIndex==-1 || searchText.charAt(frontIndex)==searchText.charAt(backIndex)){
frontIndex++;
backIndex++;
if(searchText.charAt(frontIndex)!=searchText.charAt(backIndex)){
this.next[frontIndex] = backIndex;
}else{
this.next[frontIndex] = this.next[backIndex];
}
}else{
backIndex = this.next[backIndex];
}
}
}
//从pos之后的位置搜索匹配字符串
public int KmpSearch(int pos){
int snippetIndex=pos;
int searchTextIndex=-1;
// int searchResultIndex=0;
while(snippetIndexthis.snippet.length()&&searchTextIndexthis.searchText.length()){
// searchResultIndex = snippetIndex;
if(searchTextIndex==-1||this.snippet.charAt(snippetIndex)==this.searchText.charAt(searchTextIndex)){
snippetIndex++;
searchTextIndex++;
// searchResultIndex = snippetIndex-searchTextIndex;
}else{
searchTextIndex = this.next[searchTextIndex];
}
}
return searchTextIndex >= this.next.length? snippetIndex-this.searchText.length():-1;
}
public int KmpSearch(){
return this.KmpSearch(0);
}
public static void main(String[] args) {
Kmp instance = new Kmp("ababcabcacbab");
instance.setNext("abc");
int resultIndex = instance.KmpSearch();
System.out.println(resultIndex);
}
}
next数组修正版KMP算法
标签:ext nbsp length puts style ack int main arch
原文地址:https://www.cnblogs.com/Jimmy-hacks/p/12813007.html
评论