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;
}
}

最新文章

  1. python 邮件
  2. c++中的类的对象与类的指针
  3. JQuery 的几个有用的技巧
  4. js中关于原型的几个方法
  5. 转:ASP.NET中的SESSION实现与操作方法
  6. em,pt和px之间的换算
  7. 我的Jekyll博客
  8. net use \\192.168.54.145 /user:administrator &quot;12345qwert&quot;无法连接,错误码1326
  9. EF连接MySQL数据Web.Config配置
  10. SQL 中OPENQUERY的使用
  11. DDD创始人Eric Vans:要实现DDD原始意图,必须CQRS+Event Sourcing架构
  12. bugly集成了Tinker热更新
  13. 5分钟快速入门 - Less
  14. mysql 发生系统错误 1067
  15. Catalan Number 卡特兰数
  16. redis初始化服务器
  17. Android 异步请求通用类
  18. How to Install MemSQL
  19. day12 Python列表
  20. nmon使用命令

热门文章

  1. Elasticsearch(10) --- 内置分词器、中文分词器
  2. Python学习-列表元组字典操作
  3. (七十八)c#Winform自定义控件-倒影组件
  4. 基于WeChat的消息存储备份、远程控制、小功能项目开源分享计划
  5. Robot Framework自定义测试库的作用域的理解
  6. 动态set mybatis与ibatis的写法
  7. python 列表,集合,字典,字符串的使用
  8. python爬取哦漫画
  9. linux脚本入门之终端显示输出
  10. Fast Earth - 文本 绘制,如何实现三维空间中绘制屏幕大小的文字?