zoukankan
html css js c++ java
KMP匹配算法中的失效函数
今天总算是看懂了字符串匹配算法中的KMP,记下来吧,以后查的时候方便
失效函数:设模式 P=p
0
p
1
....p
m-2
p
m-1,
则它的失效函数定义如下:
f(j)=k |当 0<=k<j 时,且使得 p0p1....pk=p
j-k
p
j-k+1
...p
j
的最大数
f(j)= -1 | 其它情况。
j
0
1
2
3
4
5
6
7
p
a
b
a
a
b
c
a
c
f(j)
-1
-1
0
0
1
-1
0
-1
详细的不记了,把算法记下来。
void
String::fail
{
int
lengthP
=
curLen;
f[
0
]
=-
1
;
for
(
int
j
=
1
;j
<
lengthP;j
++
)
{
int
i
=
f[j
-
1
];
while
(
*
(ch
+
j)
!=*
(ch
+
i
+
1
)
&&
i
>=
0
) i
=
f[i] ;
//
递推计算
if
(
*
(ch
+
j)
==*
(ch
+
i
+
1
))f[j]
=
i
+
1
;
elsef[j]
=-
1
;
}
}
下面是普通的匹配算法:
int
String::find(String
&
pat)
const
{
char
*
p
=
pat.ch;
*
s
=
ch;
int
i
=
0
;
if
(
*
p
&&
*
s)
while
(i
<=
curLen
-
pat.curLen)
if
(
*
p
++==*
s
++
)
{
//
C++的精典之处
if
(
!*
p)
return
i;
}
else
{ i
++
; s
=
ch
+
i; p
=
pat.ch; }
return
-
1
;
}
下面是 KMP 算法:
int
String::fastFind(String
&
pat)
const
{
int
posP
=
0
, pasT
=
0
;
int
lengthP
=
pat.curLen, lengthT
=
curLen;
while
(posP
<
lengthP
&&
posT
<
lengthT)
if
(pat.ch[pasP]
==
ch[posT]
{
posP
++
; posT
++
;
}
else
if
(posP
==
0
) posT
++
;
else
posP
=
pat.f[posP
-
1
]
+
1
;
if
(posP
<
lengthP)
return
-
1
;
else
return
posT
-
lengthP;
}
查看全文
相关阅读:
linux ss 网络状态工具
如何安装最新版本的memcached
如何通过XShell传输文件
mysql主从复制原理
聊聊IO多路复用之select、poll、epoll详解
聊聊 Linux 中的五种 IO 模型
pytorch中使用cuda扩展
pytorch中调用C进行扩展
双线性插值
python中的装饰器
原文地址:https://www.cnblogs.com/icehong/p/46613.html
最新文章
[Shell]Bash变量:环境变量的配置文件和登录信息
[Shell]条件判断与流程控制:if, case, for, while, until
[Shell] swoole_timer_tick 与 crontab 实现定时任务和监控
[Shell]正则表达式与通配符
linux 环境变量的设置
Ubuntu shell系统的环境变量
利用Qt Designer 进行 空间提升propomotion 的时候异常: NO such file or directory
32 bit 与 64 bit 程序(2)比较
32 bit 与 64 bit 程序(1)如何识别?
Cura
热门文章
Qt中的CSS配置(QDarkStyleSheet)
Pycharm 开发 Django 项目
Pycharm的激活码,亲测可用(20181223)
PyQt5+python3+pycharm开发环境配置
修改VS 中的代码编辑颜色-Vs主题修改
网页中的数据的4个处理方式:CRUD(Creat, Retrive, Update, Delete)
国内 Composer 镜像收集
phalcon开发工具(phalcon-devtools)
php安装phalcon扩展
关于php的mysqlnd驱动
Copyright © 2011-2022 走看看