zoukankan
html css js c++ java
Java实现KMP算法
package arithmetic;
/**
* Java实现KMP算法
*
* 思想:每当一趟匹配过程中出现字符比较不等,不需要回溯i指针,
* 而是利用已经得到的“部分匹配”的结果将模式向右“滑动”尽可能远
* 的一段距离后,继续进行比较。
*
* 时间复杂度O(n+m)
*
* @author 青梅
*
*/
public class KMPTest {
public static void main(String[] args) {
String s = "abbabbbbcab"; // 主串
String t = "bbcab"; // 模式串
char[] ss = s.toCharArray();
char[] tt = t.toCharArray();
System.out.println(KMP_Index(ss, tt)); // KMP匹配字符串
}
/**
* KMP匹配字符串
*
* @param s
* 主串
* @param t
* 模式串
* @return 若匹配成功,返回下标,否则返回-1
*/
public static int KMP_Index(char[] s, char[] t) {
int[] next = next(t);
int i = 0;
int j = 0;
while (i <= s.length - 1 && j <= t.length - 1) {
if (j == -1 || s[i] == t[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j < t.length) {
return -1;
} else
return i - t.length; // 返回模式串在主串中的头下标
}
/**
* 获得字符串的next函数值
*
* @param t
* 字符串
* @return next函数值
*/
public static int[] next(char[] t) {
int[] next = new int[t.length];
next[0] = -1;
int i = 0;
int j = -1;
while (i < t.length - 1) {
if (j == -1 || t[i] == t[j]) {
i++;
j++;
if (t[i] != t[j]) {
next[i] = j;
} else {
next[i] = next[j];
}
} else {
j = next[j];
}
}
return next;
}
}
查看全文
相关阅读:
使用log4cplus时遇到的链接错误:无法解析的外部符号 "public: static class log4cplus::Logger __cdecl log4cplus::Logger::getInstance(class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,
linux中free命令内存分析
ImportError: libmysqlclient_r.so.16: cannot open shared object file: No such file or directory
error LNK2038: 检测到“_ITERATOR_DEBUG_LEVEL”的不匹配项: 值“0”不匹配值“2
创建预编译头 Debug 正常 Release Link Error:预编译头已存在,使用第一个 PCH
C++定义字符数组
客户端数据持久化解决方案: localStorage
转:JavaScript函数式编程(三)
转: JavaScript函数式编程(二)
转:JavaScript函数式编程(一)
原文地址:https://www.cnblogs.com/qingmei/p/4120436.html
最新文章
<时间的玫瑰>读书笔记
配置Django
雪球:普通人如何合理的理财投资,有哪些书可以学习阅读?
雪球:如果让你选择一本影响你一生的好书,你会选择哪一本
<我的股票交易知识汇总与个人感悟_v1.0 (By geman)>
雪球: 关于股票的经典书籍有哪些推荐
python中urllib的urlencode与urldecode
python之psutil模块
PHP 基于 Jenkins ansible 动态选择版本进行自动化部署与回滚(第二版)
ansible常用模块
热门文章
python中的一些算法
Python中解决递归限制的问题
python中的random模块
codeMirror配置
ansible 学习笔记
django-rest-framework 使用例子
报错libtest: error while loading shared libraries: libuv.so.1: cannot open shared object file: No such file or directory
IOError: cannot open resource
linux下通过curl访问web服务器
connect()返回SOCKET_ERROR不一定就是连接失败
Copyright © 2011-2022 走看看