kmp算法,求重复字符串
2024-09-01 15:47:59
public class Demo {
public static void main(String[] args) {
String s1 = "ADBCFHABESCACDABCDABCE";
String s2 = "ABCDABCE";
int i = kmp(s1, s2);
System.out.println("下标 i="+i+" 对应字符串:"+s1.substring(14));
}
public static int kmp(String s1, String s2) {
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
int[] next=getNext(s2);
int i=0,j=0;
while (i < c1.length && j <c2.length)
{
if (j == -1 || c1[i] == c2[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == c2.length)
return i - j;
else
return -1;
}
public static int[] getNext(String s) {
char[] chars = s.toCharArray();
int[] arr = new int[chars.length];
arr[0] = -1;
int k = -1;
int j = 0;
while (j < chars.length - 1) {
//chars[k]表示前缀,chars[j]表示后缀
if (k == -1 || chars[j] == chars[k]) {
++k;
++j;
arr[j] = k;
} else {
k = arr[k];
}
System.out.println(Arrays.toString(arr));
}
return arr;
}
}
最新文章
- python 邮件
- c++中的类的对象与类的指针
- JQuery 的几个有用的技巧
- js中关于原型的几个方法
- 转:ASP.NET中的SESSION实现与操作方法
- em,pt和px之间的换算
- 我的Jekyll博客
- net use \\192.168.54.145 /user:administrator ";12345qwert";无法连接,错误码1326
- EF连接MySQL数据Web.Config配置
- SQL 中OPENQUERY的使用
- DDD创始人Eric Vans:要实现DDD原始意图,必须CQRS+Event Sourcing架构
- bugly集成了Tinker热更新
- 5分钟快速入门 - Less
- mysql 发生系统错误 1067
- Catalan Number 卡特兰数
- redis初始化服务器
- Android 异步请求通用类
- How to Install MemSQL
- day12 Python列表
- nmon使用命令