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;
}
查看全文
相关阅读:
【VB/.NET】Converting VB6 to VB.NET 【Part II】【之一】
ubuntu常用命令
mkfifo()函数
截图留念,“万能数据库查询分析器”作为关键字在百度和谷歌上的海量搜索结果
vc ado 生僻使用
[HTML5SVG]JavaScript 的新领域 动态图片处理(SVG)
中国离“过多福利”还有多远?
mysql 修改列为not null报错Invalid use of NULL value
内存泄漏与内存溢出的区别
mysql ”Invalid use of null value“ 解决方法
原文地址:https://www.cnblogs.com/icehong/p/46613.html
最新文章
基本数据结构:链表(list) C小加 C++博客
《构造正则表达式引擎》新鲜出炉啦! λcalculus(惊愕到手了欧耶,GetBlogPostIds.aspx) C++博客
groovy parttion and sql example
华润三九 感冒灵颗粒10g*9袋/盒【说明书、功效、副作用、价格】 京东好药师网上药店 这药又涨了1块钱
交易算法故障导致Knight资本集团损失超过4亿美元_IT新闻_博客园
GDB调试使用技巧 专职C++ C++博客
使用Flex图表组件
在Debian下安装Nvidia驱动
Flex编码过程
Flex开发模型
热门文章
Flex编程模型
GNU通用公共许可证( GPL)
构建Flex数据服务程序
试用笨笨兔
Linux Socket学习(一)
构建一个Flex程序
VC下的Time
第二章Getting Start with the Oracle Server(oracle入门)
求链表中倒数第K个节点
iOS网络编程iOS中解析Bonjour服务
Copyright © 2011-2022 走看看