【发布时间】:2014-11-26 06:33:50
【问题描述】:
我正在尝试实现 KMP 算法。我的算法适用于以下示例
- 文字:121121
- 图案:121
- 结果:1,4
但是当Text为12121且pattern与上面相同时,结果只是:1.我不知道这是算法的问题还是我的实现的问题?
其他例子:
- 文字:1111111111
- 图案:111
- 结果:1,4,7
我的代码是:
public class KMP {
public static void main(String[] args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String text = reader.readLine();
String pattern = reader.readLine();
search(text,pattern);
}
private static void search(String text,String pattern)
{
int[] Pi = Pi(pattern);
for (int i = 0,q=0; i <text.length()&&q<pattern.length() ; i++,q++) {
while (q>=0 && pattern.charAt(q)!=text.charAt(i))
{
q=Pi[q];
}
if(q==pattern.length()-1) {
System.out.println(i-pattern.length()+2);
q=Pi[q];
}
}
}
private static int[] Pi(String p) {
int[] Pi = new int[p.length()];
Pi[0]=-1;
int i=0;
int j=-1;
while (i<p.length()-1) {
while (j>=0 && p.charAt(j)!=p.charAt(i))
{
j=Pi[j];
}
i++;
j++;
if(p.charAt(j)==p.charAt(i)) Pi[i]=Pi[j];
else Pi[i]=j;
}
return Pi;
}
}
【问题讨论】:
-
您的算法会找到该模式的所有非重叠实例。您想查找所有重叠的实例吗?
-
我想找到该模式的所有实例。对于文本 1111 和模式 111,必须给出 2 个结果。
-
KMP 算法查找所有不重叠的实例。您必须修改算法才能在之前的搜索结果开始后重新开始搜索。
标签: java substring string-matching knuth-morris-pratt