数据结构与算法之KMP算法

短命女 2021-12-14 10:07 444阅读 0赞

数据结构与算法之KMP算法


目录

  1. KMP算法介绍
  2. 输入字符串str1,str2,返回字符串str2是否在str1中,在的话在第几位开始

1. KMP算法介绍

在CSDN上看到一篇写的很好的关于KMP的介绍,附上链接:https://www.cnblogs.com/SYCstudio/p/7194315.html


2. 输入字符串str1,str2,返回字符串str2是否在str1中,在的话在第几位开始

  1. 因为上面那篇博客说的很详细了,我直接贴代码
  2. 代码实现

    public class Code_01_KMP {

  1. public static int getIndexOf(String s, String m) {
  2. if (s == null || m == null || m.length() < 1 || s.length() < m.length()) {
  3. return -1;
  4. }
  5. char[] str1 = s.toCharArray();
  6. char[] str2 = m.toCharArray();
  7. int i1 = 0;
  8. int i2 = 0;
  9. int[] next = getNextArray(str2);
  10. while (i1 < str1.length && i2 < str2.length) {
  11. if (str1[i1] == str2[i2]) {
  12. i1++;
  13. i2++;
  14. } else if (next[i2] == -1) {
  15. //i1指向的字符和str2的第一个字符都不匹配,那么i1后移一个继续比较
  16. i1++;
  17. } else {
  18. //否则指向前一个最长前缀继续比较
  19. i2 = next[i2];
  20. }
  21. }
  22. return i2 == str2.length ? i1 - i2 : -1;
  23. }
  24. public static int[] getNextArray(char[] str2) {
  25. if (str2.length == 1) {
  26. return new int[]{
  27. -1};
  28. }
  29. int[] next = new int[str2.length];
  30. next[0] = -1;
  31. next[1] = 0;
  32. int cn = 0;
  33. int i = 2;
  34. while (i < str2.length) {
  35. if (str2[i - 1] == str2[cn]) {
  36. next[i++] = ++cn;
  37. } else if (cn > 0) {
  38. cn = next[cn];
  39. } else {
  40. next[i++] = 0;
  41. }
  42. }
  43. return next;
  44. }
  45. public static void main(String[] args) {
  46. String str = "abcabcababaccc";
  47. String match = "ababa";
  48. System.out.println(getIndexOf(str, match));
  49. }
  50. }

发表评论

表情:
评论列表 (有 0 条评论,444人围观)

还没有评论,来说两句吧...

相关阅读