public class KMPMatch { public static void main(String[] args) { String str1 = "BBC ABCDABABC DABCDABDE"; String str2 = "ABCDABD"; //String str2 = "BBC"; int[] next = KMPNext(str2); System.out.println("部分匹配表" + Arrays.toString(next)); System.out.println("匹配字段的起始位置" + KMPSearch(str1, str2, next)); // 15 } //在str1中找到str2匹配,若找到,则返回第一个字符的索引下标,否则返回 -1; public static int KMPSearch(String str1,String str2,int[] next){ //做for循环,两个string循环 for (int i=0,j=0;i<str1.length();i++){ //当匹配到不一样的时候,让J使用KMP算法的部分匹配表来重定向J while (j>0 && str1.charAt(i)!=str2.charAt(j)){ j=next[j-1]; } //当相同时候,就让j加1 if (str1.charAt(i)==str2.charAt(j)){ j++; } //当j大于str2长度的时候,就表示已经找到了 if (j>str2.length()-1){ return i-j+1; } } return -1; } // 获取一个字符串(子串)的部分匹配 public static int[] KMPNext (String str){ //定义next数组,存部分匹配值 int[] next=new int[str.length()]; //首先当只有一个值的时候,肯定是0的 next[0]=0; //然后就可以开始后面的算法 for (int i=1,j=0;i<str.length();i++){ while(j>0 && str.charAt(i)!=str.charAt(j) ){ j=next[j-1]; } //每当遇到相同的时候,则让j加1,然后把j放到next中。这个方法为什么可以呢,因为使用了KMP算法的核心,就是当他不一样的是,让j=next[j-1]。 while(str.charAt(i)==str.charAt(j)){ j++; } next[i]=j; } return next; } }
十大常用算法-KMP算法-字符串匹配问题
于 2022-10-12 09:13:39 首次发布