您的位置:首页 > 其它

【字符串】模式匹配:BF / KMP

2015-10-12 21:11 239 查看
字符串的模式匹配代码

public class KMP {
/**
* BF:穷举暴力
* @param s 文本串
* @param t 模式串
* @return 模式串在文本串中的位置
*/
public static int BF(String s,String t) {
int i = 0,j = 0;
char[] ss = s.toCharArray();
char[] tt = t.toCharArray();
while(i < ss.length && j < tt.length) {
if(ss[i] == tt[j]) {
i++;
j++;
}else {
i = i - j + 1;
j = 0;
}
}
if(j >= t.length())
return i - tt.length;
else
return -1;
}
/**
* KMP算法
* @param s 文本串
* @param t 模式串
* @return 模式串在文本串中的位置
*/
public static int KMPIndex(String s,String t) {
int[] next = getNext(t);
int i = 0,j = 0;
char[] ss = s.toCharArray();
char[] tt = t.toCharArray();
while(i < ss.length && j < tt.length) {
if(j == -1 || ss[i] == tt[j]) {
i++;
j++;
}else {
j = next[j];
}
}
if(j >= tt.length)
return i - tt.length;
else
return -1;
}
/**
* 计算模式串的next数组
* @param t 模式串
* @return 模式串的next数组
*/
public static int[] getNext(String t) {
int[] next = new int[t.length()];
int j = 0,k = -1;
next[0] = -1;
char[] tt = t.toCharArray();
while(j < tt.length - 1) {
if(k == -1 || tt[j] == tt[k]) {
j++;
k++;
next[j] = k;
}else
k = next[k];
}
return next;
}
/**
* 优化
* @param t
* @return
*/
public static int[] getNext2(String t) {
int[] next = new int[t.length()];
int j = 0,k = -1;
next[0] = -1;
char[] tt = t.toCharArray();
while(j < tt.length - 1) {
if(k == -1 || tt[j] == tt[k]) {
j++;
k++;
if(tt[j] == tt[k])
next[j] = next[k];
else
next[j] = k;
}else
k = next[k];
}
return next;
}
public static void main(String[] args) {
System.out.println(BF("aababcd", "abc"));
System.out.println(KMPIndex("aababcd", "abc"));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: