网站首页 > 基础教程 正文
KMP算法是对字符串匹配算法的一个重大改进 , 创造性的利用子串本身的特性 , 来改进算法的效率。
KMP算法的关键或则精华 , 就是在与 next[ ] 的计算。
假设存在主串 S 和 子串 T , 我们在某一趟匹配中 , 发现 T(k) != S(i+1)
那我们就得到了一个部分的匹配结果
即:T(1)……T(k-1) = S(i-k+1) …… S(i-1)
我们假设存在一个 j < k 使得: T(1)……T(j-1) = S(i-k+1)……S(i-k+j-1)
也就是说 T(1)……T(j-1) = T(k-j)……T(k-1)
所以这时我们就需要把子串向右移动 k-j 位 , 而如果 此时不存在这样的情况 , 也就是 j = 0 , 那么我们就需要向右移动 k 位
因此我们只需要求出子串中每个位置对应的 j 既可
这就是KMP算法的思想
因此next() 函数的定义如下:
0 j = 1 时
next()= max( k / 1<=k
1 当不存在上面的K且T(1) != T(j)
0 当不存在上面的K且T(1) != T(i)
求next() 函数的代码如下:
char s[100]; //被匹配字符串
char t[100]; //匹配字符串
int next[100]; //存储匹配串中每个字符应移的距离
int s_length , t_length;//被匹配串和匹配串的字符长度
void getnext()
{
int i = 0, j =-1;
next[i] = -1;
while(i < t_length)
{
while(j >= 0 && t[i] != t[j]) j = next[j]; //和该字符前面的字符比较 , 看是否和前面的字符相同
i++; j++;
if(t[i] == t[j]) next[i] = next[j];//如果当前两字符相同 ,
else next[i] = j;
}
for(i = 0; i < t_length; i++)
printf("%d\n" , next[i]);
}
//向右滑动的距离为:j-next[j]
猜你喜欢
- 2025-06-09 Java开发不可不知的20个技术点(java开发有哪些技术)
- 2025-06-09 探秘Java面试中问的最多的String、StringBuffer、StringBuilder
- 2025-06-09 一个字符串中到底能有多少个字符?我竟然算错了
- 2025-06-09 你只会用 SB?试试 StringJoiner,真香
- 2025-06-09 Java基础之String与int两者之间如何相互转换?
- 2025-06-09 Java之String对象深入理解(java中string对象特点)
- 2025-06-09 Java枚举你真的会用吗(java枚举如何使用)
- 2025-06-09 吊打面试官(十)--Java语言中字符串相关处理一文全掌握
- 2025-06-09 Java Array 和 String 的转换(java array转set)
- 2025-06-09 JAVA面试|String、StringBuffer、StringBuilder区别以及场景应用
- 06-09Socioeconomic growth goals high on meetings' agenda
- 06-09Cities Along Middle Reaches of Yangtze River Agree on 63 Cooperation Items
- 06-09Scientists to make flag flutter on moon
- 06-09CBN丨Foreign-funded institutions bullish on Chinese assets
- 06-09Full Text: Joint Statement between the People's Republic of China and the French Republic on Climate Change on the occasion of the Tenth Anniversary of the Paris Agreement
- 06-092022年底总结,温暖和激励自己的文案
- 06-09百度实时推送代码解决方案(百度实时推送工具)
- 06-09PHP漏洞之跨网站请求伪造(php跨站脚本攻击)
- 最近发表
-
- Socioeconomic growth goals high on meetings' agenda
- Cities Along Middle Reaches of Yangtze River Agree on 63 Cooperation Items
- Scientists to make flag flutter on moon
- CBN丨Foreign-funded institutions bullish on Chinese assets
- Full Text: Joint Statement between the People's Republic of China and the French Republic on Climate Change on the occasion of the Tenth Anniversary of the Paris Agreement
- 2022年底总结,温暖和激励自己的文案
- 百度实时推送代码解决方案(百度实时推送工具)
- PHP漏洞之跨网站请求伪造(php跨站脚本攻击)
- ThinkPHP后台入口地址查找(thinkphp build.php)
- PHP新手如何提高代码质量(php新手如何提高代码质量的方法)
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- deletesql (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)