import java.util.Arrays;
/**
* KMP算法的基本思路是分析模式串,如果当前位置比较出错(之前的位置都匹配成功),则指向模式串的下标调到下一个符合模式的位置
* 比如 abcabcd中,当前下标指向d,d不匹配,由于d前面的abc与模式串前缀的abc相同,所以无需重新表abc,下标指向第二个a
*
* KMP算法获取next数组的方式与匹配的方式紧密相关,以下介绍一种KMP的匹配算法
* next数组中记录如果后一个位置比较错误,下标重新开始的位置,
* 匹配函数中先比较再处理,如果j==0就左移主串,所以next数组中不需要设置next[0]=-1作为标识
* 比如模式串"abcabcd",next[]={0, 0, 0, 1, 2, 3, 0},假如当前下标指向d,d不匹配,下标指向3,即第二个a
*
*
*/
public class TestKMP {
public static int[] getNext2(String scheme) {
int[] result = new int[scheme.length()];
char[] src = scheme.toCharArray();
result[0] = 0;
int i=1, j=0;
for(;i<src.length;i++){
j=result[i-1];
while(j>0&&src[j]!=src[i]){
j=result[j-1];
}
if(j>=0&&src[j]==src[i]){
result[i] = j+1;
}else{
result[i] = 0;
}
}
return result;
}
public static void pattern2(String str, String sub, int[] next) {
char[] ch1 = str.toCharArray();
char[] ch2 = sub.toCharArray();
int i = 0, j = 0; // i控制ch1,j控制ch2;
for (; i < ch1.length;) {
if (ch1[i] == ch2[j]) {// 匹配就自动递增,往后匹配。
if (j == ch2.length - 1) {
System.out.println(i - ch2.length + 1);
break;
}
j++;
i++;
}else if(j==0){
i++;
}else {
j = next[j-1] ;
}
}
}
public static int[] getNext(String scheme) {
int[] result = new int[scheme.length()];
char[] src = scheme.toCharArray();
result[0] = -1;
int i=1, j=0;
for(;i<src.length;i++){
j=result[i-1];
while(j>=0&&src[j+1]!=src[i]){
j=result[j-1];
}
if(src[j+1]==src[i]){
result[i] = j+1;
}else{
result[i] = -1;
}
}
return result;
}
public static void pattern(String str, String sub, int[] next) {
char[] ch1 = str.toCharArray();
char[] ch2 = sub.toCharArray();
int i = 0, j = 0; // i控制ch1,j控制ch2;
for (; i < ch1.length;) {
if (ch1[i] == ch2[j]) {// 匹配就自动递增,往后匹配。
if (j == ch2.length - 1) {
System.out.println(i - ch2.length + 1);
break;
}
j++;
i++;
} else if (j == 0) {
i++;
} else {
j = next[j - 1] + 1;
}
}
}
public static void main(String[] args) {
pattern2("abcdeabcdeabcdf","cdf", getNext2("abcdeabcdeabcdf"));
pattern("abcdeabcdeabcdf", "cdf", getNext("abcdeabcdeabcdf"));
}
}
KMP算法
最新推荐文章于 2023-04-09 17:43:52 发布