1、串的模式匹配算法
前端时间在复习KMP算法时在网上看到了一篇关于KMP的博文,讲的非常详细,在这里给大家分享下:点击打开链接
在串的模式匹配算法中主要有两种算法,BF算法与KMP算法,在这里我不准备详细介绍这两种方法,我主要向大家展示这两种算法的实现。
2、附源码
index.java
package com.jz.index;
public class Index {
//根据KMP算法,next数组用于存放子串中每一个位子匹配失败后下次滑动到的位置
public static int[] getNext(String ps) {
char[] p = ps.toCharArray();
int[] next = new int[p.length];
next[0] = -1;
int j = 0;
int k = -1;
while (j < p.length - 1) {
if (k == -1 || p[j] == p[k]) {
j++;
k++;
next[j] = k;
} else {
k = next[k];
}
}
return next;
}
public static int Index_KMP(String ts,String ps) {
char[] t = ts.toCharArray();
char[] p = ps.toCharArray();
int[] next=getNext(ps);
int i=0;
int j=0;
for(i=0;i<t.length;) {
if(j==-1||t[i]==p[j]) {
i++;
j++;
}
else if(t[i]!=p[j]){
j=next[j];
}
//遍历完子串则查找成功,返回位置
if(j==p.length)
return i-p.length;
}
//遍历完母串,没有遍历完子串,查找失败
return -1;
}
//BF算法,返回子串ps在母串ts中的位置
public static int Index_BF(String ts,String ps) {
char[] t = ts.toCharArray();
char[] p = ps.toCharArray();
int i=0;
int j=0;
//遍历母串
while(i<t.length) {
//遍历子串
while(j<p.length) {
//子串的字符与母串字符相同
if(t[i]==p[j]) {
i++;
j++;
}
else {
//子串字符与母串字符不相同,回溯,子串从头开始,母串回到i-j-1位置
i=i-j+1;
j=0;
}
//母串已经遍历完,跳出循环
if(i==t.length) {
break;
}
}
//母串遍历完,子串还未遍历完,跳出循环,返回失败
if(i==t.length&&j!=p.length) {
break;
}
else{
//子串遍历完,母串还未遍历完,查找成功,返回位置
return i-p.length;
}
}
return -1;
}
}
Test.java
package com.jz.index;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String ts=new String("aaswbxbacx");
String ps=new String("bac");
int index = Index.Index_KMP(ts, ps);
int index2 = Index.Index_BF(ts, ps);
System.out.println(index);
System.out.println(index2);
}
}
附:限于编者编程与理解能力,欢迎各位读者批评指正。
以上内容皆为作者原创,转载请注明出处