<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="/scripts/pretty-feed-v3.xsl" type="text/xsl"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:h="http://www.w3.org/TR/html4/"><channel><title>heresAgu</title><description>记录计算机科学、人工智能与技术学习的个人博客</description><link>https://heresagu-blog.vercel.app</link><item><title>KMP 算法</title><link>https://heresagu-blog.vercel.app/blog/20261021-kmp-algorithm/post</link><guid isPermaLink="true">https://heresagu-blog.vercel.app/blog/20261021-kmp-algorithm/post</guid><description>从朴素字符串匹配出发，理解最长相等真前后缀、前缀函数与 KMP 的失配跳转，并给出 C++ 实现。</description><pubDate>Wed, 21 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;为什么我打算写这篇文章？
我在去年粗略的学习了一遍基础算法，不过现在忘了。正好今天数据结构课老师提了一嘴。
心血来潮，打算重温一遍这坨。
也当是给我写博客练个手。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;本文主要对象还是入门算法的学生，&lt;strong&gt;至于会kmp的建议立即划走&lt;/strong&gt;。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;这是我在我的博客上，打算记录的第一篇文章，或者说也可以是笔记。
我会在这篇笔记完成后，将我之前写过的分类型基础算法题型，整理完上传。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;什么是KMP算法？&lt;/h2&gt;
&lt;p&gt;KMP（Knuth–Morris–Pratt）算法是数据结构中经典的字符串模式匹配算法。
主要应对的是：字符串匹配问题，比如：
给定两个字符串：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;主串（&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;T&lt;/mi&gt;&lt;mi&gt;e&lt;/mi&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mi&gt;t&lt;/mi&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;Text&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;）：&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;T&lt;/mi&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mi mathvariant=&quot;normal&quot;&gt;&quot;&lt;/mi&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;mi&gt;b&lt;/mi&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;mi&gt;b&lt;/mi&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;mi&gt;b&lt;/mi&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;mi&gt;c&lt;/mi&gt;&lt;mi mathvariant=&quot;normal&quot;&gt;&quot;&lt;/mi&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;T = &quot;abababac&quot;&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;模式串（&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;P&lt;/mi&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;mi&gt;t&lt;/mi&gt;&lt;mi&gt;t&lt;/mi&gt;&lt;mi&gt;e&lt;/mi&gt;&lt;mi&gt;r&lt;/mi&gt;&lt;mi&gt;n&lt;/mi&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;Pattern&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;）：&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;P&lt;/mi&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mi mathvariant=&quot;normal&quot;&gt;&quot;&lt;/mi&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;mi&gt;b&lt;/mi&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;mi&gt;b&lt;/mi&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;mi&gt;c&lt;/mi&gt;&lt;mi mathvariant=&quot;normal&quot;&gt;&quot;&lt;/mi&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;P = &quot;ababac&quot;&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;我们需要找到模式串 P 在主串 T 中第一次出现的位置。&lt;/p&gt;
&lt;p&gt;它的核心思想是：当匹配失败时，利用已经匹配过的字符信息，避免重复比较。&lt;/p&gt;
&lt;h2&gt;我们先回顾下，一般我们匹配字符串的方式&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;c语言中&lt;/strong&gt;，使用&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;strcmp(a,b)==0;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;判断&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;a&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;、&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;b&lt;/mi&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;b&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;两个字符串是否相等。&lt;code&gt;strcmp(a, b)&lt;/code&gt; 会逐个比较字符，直到遇到不同字符或字符串结束：两个字符串完全相等时返回&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;0&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;；不相等时，根据第一个不同字符的大小关系返回负数或正数，并不保证是&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mo&gt;−&lt;/mo&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;-1&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;或&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;1&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;。因此，&lt;code&gt;strcmp(a, b) == 0&lt;/code&gt; 这个比较表达式的结果才是&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;1&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;（相等）或&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;0&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;（不相等）。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;对于普通匹配算法&lt;/strong&gt;
最简单的方法是从主串的某个位置开始，逐个比较字符。
&lt;img src=&quot;https://heresagu-blog.vercel.app/_astro/%E5%9B%BE%E7%89%871.DcbhzIbn_1r5TtB.webp&quot; alt=&quot;KMP 失配后复用已匹配字符的示意图&quot;&gt;&lt;/p&gt;
&lt;p&gt;普通算法遇到失败，就将模式串向右移动一位，重新比较。
我们发现，如果一匹配失败就直接进行下一个位置的从&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;0&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;开始的比较，会浪费许多信息。
像这里，已经成功匹配了&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;mi&gt;b&lt;/mi&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;mi&gt;b&lt;/mi&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt; ababa&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;，如果直接重新开始，就会重复比较许多字符。&lt;/p&gt;
&lt;p&gt;那么，这么充分利用上这段&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;mi&gt;b&lt;/mi&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;mi&gt;b&lt;/mi&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;ababa&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;，已配对成功的信息呢？
kmp算法可以帮助我们记录这个信息，从而优化配对时间。
朴素匹配算法最坏需要 &lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;O&lt;/mi&gt;&lt;mo stretchy=&quot;false&quot;&gt;(&lt;/mo&gt;&lt;mi&gt;n&lt;/mi&gt;&lt;mi&gt;m&lt;/mi&gt;&lt;mo stretchy=&quot;false&quot;&gt;)&lt;/mo&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;O(nm)&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt; 时间，而 KMP 可以做到&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;O&lt;/mi&gt;&lt;mo stretchy=&quot;false&quot;&gt;(&lt;/mo&gt;&lt;mi&gt;n&lt;/mi&gt;&lt;mo&gt;+&lt;/mo&gt;&lt;mi&gt;m&lt;/mi&gt;&lt;mo stretchy=&quot;false&quot;&gt;)&lt;/mo&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;O(n+m)&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;&lt;/p&gt;
&lt;h2&gt;KMP的思想&lt;/h2&gt;
&lt;p&gt;我们观察原图&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://heresagu-blog.vercel.app/_astro/%E5%9B%BE%E7%89%871.DcbhzIbn_1r5TtB.webp&quot; alt=&quot;KMP 失配后复用已匹配字符的示意图&quot;&gt;&lt;/p&gt;
&lt;p&gt;它的模式串a b a b a，有一个非常重要的特点：
它的开头是a b a ，而它的结尾也是a b a&lt;/p&gt;
&lt;p&gt;所以，如果我们把模式串向右移动两位的话，&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;T:     a b a b a b a c
P:         a b a b a c
           ✓ ✓ ✓
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;不难发现，由于它的前后缀相同，和朴素比较算法相比，我们可以从第四个字符开始比较，而不是第一个。&lt;/p&gt;
&lt;p&gt;因此， KMP 的关键，就是利用已经匹配部分的前缀和后缀相等这一性质，避免重复比较。&lt;/p&gt;
&lt;p&gt;不过，这样引出几个问题：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;为什么一定要找前缀与后缀？&lt;/li&gt;
&lt;li&gt;如果有多个相等的前后缀，应该选择哪一个？&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;理解KMP算法的具体原理流程&lt;/h2&gt;
&lt;h3&gt;回答问题&lt;/h3&gt;
&lt;p&gt;先给出结论：
我们需要前后缀，是因为，相同的前后缀，才能在移动模式串的部分后，能够做到头尾重合。
对于多个相等的真前后缀，我们关心的是&lt;strong&gt;最长相等真前后缀&lt;/strong&gt;。说人话就是，不是自己的，最长的前后缀。&lt;/p&gt;
&lt;p&gt;我们不对前后缀定义展开，这里只用例子解释：
令 S = &quot;ababa&quot;
那么它的前缀包括a，ab，aba，abab，ababa。后缀同理。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://heresagu-blog.vercel.app/_astro/%E5%9B%BE%E7%89%871.DcbhzIbn_1r5TtB.webp&quot; alt=&quot;KMP 失配后复用已匹配字符的示意图&quot;&gt;&lt;/p&gt;
&lt;p&gt;在一次匹配失败后，只希望把模式串向右移动。我们发现，如果想要移动到有重合部分的那个位置（第三位），为了保证重叠的部分仍然匹配，模式串的新前缀就必须等于旧匹配部分的某个后缀。
又发现，假如我们不取最长的，非本身的相同前后缀（比如a，a），那么&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;P:         a b a b a b a c
P’:                a b a b a c
               ?   ✓ 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;从这个思路本身来说，我们可能会漏掉结果。
从朴素算法的角度考虑，第一次，我们匹配了5个符号，第二次，a!=b,匹配失败。我们肯定希望不漏过前面任何可能的结果。
因此，这就解释了为什么 KMP 需要记录「最长相等真前后缀长度」。&lt;/p&gt;
&lt;h3&gt;具体的流程是什么？&lt;/h3&gt;
&lt;p&gt;前面所提的最长相等真前后缀长度，是KMP调用信息的关键。
我们用前缀函数 &lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;p&lt;/mi&gt;&lt;mi&gt;i&lt;/mi&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;pi&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;（也经常被称为 LPS 数组），来记录这个信息。&lt;/p&gt;
&lt;p&gt;设模式串为：&lt;/p&gt;
&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot; display=&quot;block&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;P&lt;/mi&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;msub&gt;&lt;mi&gt;p&lt;/mi&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/msub&gt;&lt;msub&gt;&lt;mi&gt;p&lt;/mi&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/msub&gt;&lt;mo&gt;⋯&lt;/mo&gt;&lt;msub&gt;&lt;mi&gt;p&lt;/mi&gt;&lt;mrow&gt;&lt;mi&gt;m&lt;/mi&gt;&lt;mo&gt;−&lt;/mo&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mrow&gt;&lt;/msub&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;P=p_0p_1\cdots p_{m-1}&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;
&lt;p&gt;定义：&lt;/p&gt;
&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot; display=&quot;block&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;menclose notation=&quot;box&quot;&gt;&lt;mstyle scriptlevel=&quot;0&quot; displaystyle=&quot;false&quot;&gt;&lt;mstyle scriptlevel=&quot;0&quot; displaystyle=&quot;false&quot;&gt;&lt;mstyle scriptlevel=&quot;0&quot; displaystyle=&quot;true&quot;&gt;&lt;mrow&gt;&lt;mi&gt;π&lt;/mi&gt;&lt;mo stretchy=&quot;false&quot;&gt;[&lt;/mo&gt;&lt;mi&gt;i&lt;/mi&gt;&lt;mo stretchy=&quot;false&quot;&gt;]&lt;/mo&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mtext&gt;字符串 &lt;/mtext&gt;&lt;mi&gt;P&lt;/mi&gt;&lt;mo stretchy=&quot;false&quot;&gt;[&lt;/mo&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;mo&gt;…&lt;/mo&gt;&lt;mi&gt;i&lt;/mi&gt;&lt;mo stretchy=&quot;false&quot;&gt;]&lt;/mo&gt;&lt;mtext&gt; 的最长相等真前后缀长度&lt;/mtext&gt;&lt;/mrow&gt;&lt;/mstyle&gt;&lt;/mstyle&gt;&lt;/mstyle&gt;&lt;/menclose&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;\boxed{
\pi[i]=
\text{字符串 }P[0\ldots i]\text{ 的最长相等真前后缀长度}
}&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;
&lt;p&gt;注意：
&lt;strong&gt;这里计算的并不是完整模式串的前后缀。&lt;/strong&gt;这个我们后面还会提及。
而是对于每一个 i，都取：&lt;/p&gt;
&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot; display=&quot;block&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;P&lt;/mi&gt;&lt;mo stretchy=&quot;false&quot;&gt;[&lt;/mo&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;mo&gt;…&lt;/mo&gt;&lt;mi&gt;i&lt;/mi&gt;&lt;mo stretchy=&quot;false&quot;&gt;]&lt;/mo&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;P[0\ldots i]&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;
&lt;p&gt;这个从开头到当前位置的子串，再计算它的最长相等真前后缀长度。
例如：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;P = &quot;ababac&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;前缀函数计算表&lt;/p&gt;
&lt;p&gt;| i | P[0..i] | 最长相等真前后缀 | pi[i] |
| --- | --- | --- | --- |
| 0 | a | 无 | 0 |
| 1 | ab | 无 | 0 |
| 2 | aba | a | 1 |
| 3 | abab | ab | 2 |
| 4 | ababa | aba | 3 |
| 5 | ababac | 无 | 0 |&lt;/p&gt;
&lt;p&gt;最终结果&lt;/p&gt;
&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot; display=&quot;block&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;menclose notation=&quot;box&quot;&gt;&lt;mstyle scriptlevel=&quot;0&quot; displaystyle=&quot;false&quot;&gt;&lt;mstyle scriptlevel=&quot;0&quot; displaystyle=&quot;false&quot;&gt;&lt;mstyle scriptlevel=&quot;0&quot; displaystyle=&quot;true&quot;&gt;&lt;mrow&gt;&lt;mtext&gt;pi&lt;/mtext&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mo stretchy=&quot;false&quot;&gt;[&lt;/mo&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;mo separator=&quot;true&quot;&gt;,&lt;/mo&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;mo separator=&quot;true&quot;&gt;,&lt;/mo&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;mo separator=&quot;true&quot;&gt;,&lt;/mo&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;mo separator=&quot;true&quot;&gt;,&lt;/mo&gt;&lt;mn&gt;3&lt;/mn&gt;&lt;mo separator=&quot;true&quot;&gt;,&lt;/mo&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;mo stretchy=&quot;false&quot;&gt;]&lt;/mo&gt;&lt;/mrow&gt;&lt;/mstyle&gt;&lt;/mstyle&gt;&lt;/mstyle&gt;&lt;/menclose&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;\boxed{
\text{pi} = [0, 0, 1, 2, 3, 0]
}&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;
&lt;p&gt;这个数组有什么作用？
之前我们的例子，已经成功匹配了五个字符，最后一位失配：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;P[0..4] = &quot;ababa&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;发生失配后，我们想知道最多能够保留多少个已匹配字符。
直接查：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;pi[j - 1];
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;也就是：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;pi[4] = 3;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;我们将&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;j&lt;/mi&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;j&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;赋值，也就是把模式串的匹配位置，从&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mn&gt;5&lt;/mn&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;5&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;（配对失败的位置），改到&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mn&gt;3&lt;/mn&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;3&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;（下一轮配对的位置）。注意，如果是朴素算法，和&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;K&lt;/mi&gt;&lt;mi&gt;M&lt;/mi&gt;&lt;mi&gt;P&lt;/mi&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;KMP&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;不同了，第二轮会改到0。&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;j = pi[j - 1];  // j 从 5 变成 3
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这样，我们就可以开始一整轮的解释。&lt;/p&gt;
&lt;h3&gt;算法过程&lt;/h3&gt;
&lt;p&gt;我们先不考虑，pi数组的求解算法，先默认我们已经有这个数组。&lt;/p&gt;
&lt;p&gt;我们令，&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;i&lt;/mi&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;i&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt; 是主串目前匹配的位置，&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;mi&gt;j&lt;/mi&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;j&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;为模式串目前匹配的位置。
我们要先知道，i实际上，在整个匹配过程中，是不会回退的。
这里要先和朴素算法区分：朴素算法中，模式串和主串匹配，如果失败了，比如&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;T:     a b a b a b a c
                 i
P:     a b a b a c
                 j
       ✓ ✓ ✓ ✓✓ x
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;朴素算法中，i=5会回到i=1，j=5回到j=0。所以朴素算法会有一个参数k来记录这轮本来是从哪个位置开始比较的。
而KMP不同，i不会回退，还会是i=5，或者更大。例如下一步：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;T:     a b a b a b a c
                 i
P:         a b a b a c
                 j 
           ✓ ✓ ✓
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;i仍然是5，变化的只是j的位置，从j=5回到j=3。
所以，当我们有了pi数组，我们可以直接通过公式&lt;/p&gt;
&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot; display=&quot;block&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;menclose notation=&quot;box&quot;&gt;&lt;mstyle scriptlevel=&quot;0&quot; displaystyle=&quot;false&quot;&gt;&lt;mstyle scriptlevel=&quot;0&quot; displaystyle=&quot;false&quot;&gt;&lt;mstyle scriptlevel=&quot;0&quot; displaystyle=&quot;true&quot;&gt;&lt;mrow&gt;&lt;mi&gt;j&lt;/mi&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mi&gt;p&lt;/mi&gt;&lt;mi&gt;i&lt;/mi&gt;&lt;mo stretchy=&quot;false&quot;&gt;[&lt;/mo&gt;&lt;mi&gt;j&lt;/mi&gt;&lt;mo&gt;−&lt;/mo&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;mo stretchy=&quot;false&quot;&gt;]&lt;/mo&gt;&lt;/mrow&gt;&lt;/mstyle&gt;&lt;/mstyle&gt;&lt;/mstyle&gt;&lt;/menclose&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;\boxed{
j = pi[j-1]
}&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;
&lt;p&gt;让j指针直接指向可以匹配的位置。这样的话，可以继续匹配：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;i = 6;
j = 4;
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;这里有一点：我们如何理解这个pi数组，这个变化，是j减少，还是模式串平移呢？
我认为看成j减少，本质上，j是跳转到前一个能够和前缀重合的一个后缀位置，这个长度是最长后缀的长度，所以是j减少了pi数据的距离。当然，正反都说得通。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;这就是KMP算法如何跳转的流程。&lt;/p&gt;
&lt;p&gt;最后要说的，就是如何得到这个pi数组了。&lt;/p&gt;
&lt;h3&gt;pi数组的求解&lt;/h3&gt;
&lt;p&gt;回顾定义：&lt;/p&gt;
&lt;span class=&quot;katex&quot;&gt;&lt;math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot; display=&quot;block&quot;&gt;&lt;semantics&gt;&lt;mrow&gt;&lt;menclose notation=&quot;box&quot;&gt;&lt;mstyle scriptlevel=&quot;0&quot; displaystyle=&quot;false&quot;&gt;&lt;mstyle scriptlevel=&quot;0&quot; displaystyle=&quot;false&quot;&gt;&lt;mstyle scriptlevel=&quot;0&quot; displaystyle=&quot;true&quot;&gt;&lt;mrow&gt;&lt;mtext&gt;pi&lt;/mtext&gt;&lt;mo stretchy=&quot;false&quot;&gt;[&lt;/mo&gt;&lt;mi&gt;i&lt;/mi&gt;&lt;mo stretchy=&quot;false&quot;&gt;]&lt;/mo&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mi&gt;P&lt;/mi&gt;&lt;mo stretchy=&quot;false&quot;&gt;[&lt;/mo&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;mo&gt;…&lt;/mo&gt;&lt;mi&gt;i&lt;/mi&gt;&lt;mo stretchy=&quot;false&quot;&gt;]&lt;/mo&gt;&lt;mtext&gt; 的最长相等真前后缀长度&lt;/mtext&gt;&lt;/mrow&gt;&lt;/mstyle&gt;&lt;/mstyle&gt;&lt;/mstyle&gt;&lt;/menclose&gt;&lt;/mrow&gt;&lt;annotation encoding=&quot;application/x-tex&quot;&gt;\boxed{\text{pi}[i]=P[0\ldots i]\text{ 的最长相等真前后缀长度}}&lt;/annotation&gt;&lt;/semantics&gt;&lt;/math&gt;&lt;/span&gt;
&lt;p&gt;这里必须注意：pi[i] 考虑的是 从 P[0] 到 P[i] 这一段字符串，不一定是完整的模式串。
我们用的方法是，利用已经计算出的 pi[0] 到 pi[i-1]，高效地计算 pi[i]。&lt;/p&gt;
&lt;p&gt;假设我们已经计算到：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;下标:  0 1 2 3 4 5 6
P:     a a b a a a b
pi:    0 1 0 1 2 ? ?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;现在要计算：pi[5]，即：P[0..5] = &quot;aabaaa&quot;
我们已经知道：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;pi[4] = 2;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这说明：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;P[0..4] = &quot;aabaa&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;的最长相等真前后缀长度是 2。
也就是&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;             P[0..4]
下标:       0 1 2 3 4                      0 1 2 3 4 5
字符:       a a b a a           --&gt;        a a b a a a
             └─┘                                     ↑
                   └─┘
             前缀aa = 后缀aa                         新字符
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;如果 &lt;code&gt;P[2] == P[5]&lt;/code&gt;，原来长度为 &lt;code&gt;pi[4] = 2&lt;/code&gt; 的相等真前后缀就能再延长一位，所以 &lt;code&gt;pi[5] = pi[4] + 1 = 3&lt;/code&gt;。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;不过，这里P[2] != P[5]，那怎么办？
虽然长度 3 不行，但可能存在长度 2 或长度 1 的相等真前后缀。
我们尝试，在这串字符的前缀中，找到和这串字符后缀相同的部分，这就像是找模式串和主串，像是自己和自己做KMP算法！&lt;/p&gt;
&lt;p&gt;我们将前缀看成模式串，后缀看成主串。我们的目标，就是在前缀中，找到一个更小的前缀，能够和我的后缀的新后缀匹配。&lt;/p&gt;
&lt;p&gt;那，参考KMP的流程，我们可以找这个旧前缀的 &lt;strong&gt;「最长相等真前后缀长度」&lt;/strong&gt;。&lt;/p&gt;
&lt;p&gt;这样，新前缀的开头，就和旧前缀的新后缀相同，自然，和旧后缀产生的新后缀相同。&lt;/p&gt;
&lt;p&gt;具体来说，原本的aabaa，旧前缀是aa（0，1），旧后缀是aa（3，4）。
旧前缀产生的新前缀是a（0），新后缀是a（1）。
旧后缀产生的新前缀是a（3），新后缀是a（4）。
a（0），和a（4），一定是相同的。这个a，不只是具体的a，对于任何相同的结构都成立。
接着，我们只要比较新位置的a（5），是否等于a（1）即可。&lt;/p&gt;
&lt;p&gt;如果相同，就得到答案了；如果不同：又回到那个比较b（2）和a（5）的起点，我们的做法还是一样，找新的新前缀的最长相等真前后缀长度。&lt;/p&gt;
&lt;p&gt;这个过程就是一个循环，直到最后，没有能匹配的长度，说明，pi[5]=0，得到结果。&lt;/p&gt;
&lt;p&gt;整个pi数组的求解就是如此。&lt;/p&gt;
&lt;h2&gt;代码&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;#x3C;bits/stdc++.h&gt;
using namespace std;

vector&amp;#x3C;int&gt; build_pi(const string&amp;#x26; p) {
    int m = (int)p.size();
    vector&amp;#x3C;int&gt; pi(m, 0);

    for (int i = 1; i &amp;#x3C; m; ++i) {
        int j = pi[i - 1];
        while (j &gt; 0 &amp;#x26;&amp;#x26; p[i] != p[j]) {
            j = pi[j - 1];
        }
        if (p[i] == p[j]) {
            ++j;
        }
        pi[i] = j;
    }
    return pi;
}

int kmp_find(const string&amp;#x26; text, const string&amp;#x26; pattern) {
    int n = (int)text.size();
    int m = (int)pattern.size();
    if (m == 0) return 0;

    vector&amp;#x3C;int&gt; pi = build_pi(pattern);
    int j = 0;
    for (int i = 0; i &amp;#x3C; n; ++i) {
        while (j &gt; 0 &amp;#x26;&amp;#x26; text[i] != pattern[j]) {
            j = pi[j - 1];
        }
        if (text[i] == pattern[j]) {
            ++j;
        }
        if (j == m) {
            return i - m + 1;
        }
    }
    return -1;
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(nullptr);

    string text, pattern;
    getline(cin, text);
    getline(cin, pattern);
    cout &amp;#x3C;&amp;#x3C; kmp_find(text, pattern) &amp;#x3C;&amp;#x3C; &apos;\n&apos;;
    return 0;
}
&lt;/code&gt;&lt;/pre&gt;</content:encoded></item><item><title>Hello World</title><link>https://heresagu-blog.vercel.app/blog/helloworld/post</link><guid isPermaLink="true">https://heresagu-blog.vercel.app/blog/helloworld/post</guid><description>我的第一篇博客</description><pubDate>Mon, 21 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;hr&gt;
&lt;h1&gt;Hello World&lt;/h1&gt;
&lt;p&gt;这是我的第一篇博客。&lt;/p&gt;
&lt;p&gt;以后我会在这里记录：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Transformer&lt;/li&gt;
&lt;li&gt;PyTorch&lt;/li&gt;
&lt;li&gt;CSAPP&lt;/li&gt;
&lt;li&gt;数据结构&lt;/li&gt;
&lt;li&gt;科研学习&lt;/li&gt;
&lt;/ul&gt;</content:encoded></item></channel></rss>