kmp 快速模式串匹配
题目要求:输入一个str串,输入一个将要匹配的match串,若匹配成功,返回match在str中的第一个位置,否则返回-1
举例 : str :abc123
match: 123
返回 3
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner s=new Scanner(System.in);
String str=s.nextLine();
String match=s.nextLine();
System.out.println(getIndexOf(str,match));
}
public static int getIndexOf(String str,String match){
if(str==null|| match==null || match.length()<1 || match.length()> str.length())
return -1;
char []ss=str.toCharArray(); char []ms=match.toCharArray(); int []next=getNextArray(ms);
int si=0; int mi=0;
while(si<ss.length && mi<ms.length){
if(ss[si] == ms[mi]){
si++; mi++;
}else if(next[mi] == -1)
si++;
else
mi=next[mi];
}
return mi==ms.length ? si-mi :-1;
}
public static int[] getNextArray( char []ms){ //求next数组
if(ms.length == 1)
return new int[]{-1};
int []next=new int[ms.length];
next[0] = -1; next[1] = 0;
int pos = 2; int cn = 0;
while(pos<ms.length){
if(ms[pos-1] == ms[cn])
next[pos++] = ++cn;
else if(cn > 0)
cn=next[cn];
else
next[pos++]=0;
}
return next;
}
}