博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
KMP算法
阅读量:4309 次
发布时间:2019-06-06

本文共 1507 字,大约阅读时间需要 5 分钟。

1 public class Main { 2  3     public static void main(String[] args) { 4         String s = "abcabcababaccc"; 5         String m = "ab"; 6          7         System.out.println(getIndex(s, m)); 8     } 9 10     public static int getIndex(String s, String m) {11         if(s.length() < m.length()) {12             return -1;13         }14 15         char[] str1 = s.toCharArray();16         char[] str2 = m.toCharArray();17         18         int i1 = 0;19         int i2 = 0;20 21         int[] next = getNextArray(str2);22 23         while(i1 < str1.length && i2 < str2.length) {24             if(str1[i1] == str2[i2]) {25                 i1++;26                 i2++;27             } else if(next[i2] == -1) {28                 i1++;29             } else {30                 i2 = next[i2];31             }32         }33 34         return i2 == str2.length?i1-i2:-1;35     }36 37     public static int[] getNextArray(char[] str) {38         if(str.length == 1) {39             return new int[]{-1};40         }41 42         int[] next = new int[str.length];43         next[0] = -1;44         next[1] = 0;45 46         int i = 2;47         int cn = 0;48 49         while(i < next.length) {50             if(str[i-1] == str[cn]) {51                 next[i++] = ++cn;52             } else if(cn > 0) {53                 cn = next[cn];54             } else {55                 next[i++] = 0;56             }57         }58 59         return next;60     }61 }

 

转载于:https://www.cnblogs.com/wylwyl/p/10512979.html

你可能感兴趣的文章
HIVE—索引、分区和分桶的区别
查看>>
Hive进阶总结(听课总结)
查看>>
大数据领域两大最主流集群管理工具Ambari和Cloudera Manger
查看>>
Sqoop往Hive导入数据实战
查看>>
Mysql到HBase的迁移
查看>>
Sqoop import进阶
查看>>
Hive语句是如何转化成MapReduce任务的
查看>>
Hive创建table报错:Permission denied: user=lenovo, access=WRITE, inode="":suh:supergroup:rwxr-xr-x
查看>>
Hive执行job时return code 2排查
查看>>
hive常用函数及数据结构介绍
查看>>
Hive面试题干货(亲自跟着做了好几遍,会了的话对面试大有好处)
查看>>
力扣题解-230. 二叉搜索树中第K小的元素(递归方法,中序遍历解决)
查看>>
力扣题解-123. 买卖股票的最佳时机 III(动态规划)
查看>>
Django 源码阅读:服务启动(wsgi)
查看>>
Django 源码阅读:url解析
查看>>
Docker面试题(一)
查看>>
第一轮面试题
查看>>
2020-11-18
查看>>
Docker面试题(二)
查看>>
一、redis面试题及答案
查看>>