KMP模式匹配算法
朴素的模式匹配算法
主串为,我们要匹配。定义两个指针 ,分别指向字符串。
最初, 指向两个字符串的头,将两个字符串的头对其,开始同步向后移动两个指针,当 时,发现,这时就将 相对 整体向右移动一位, 指针不变,令 回到 。此时发现 的第一个字符就不匹配,继续进行如图的步骤。
朴素算法的最坏时间复杂度为,这样的算法实在是不能接受的。
KMP算法概述
在计算机科学中, 字符串查找算法(简称为算法)可在一个主文本字符串 内查找一个词 的出现位置。此算法通过运用对这个词在不匹配时本身就包含足够的信息来确定下一个匹配将在哪里开始的发现,从而避免重新检查先前匹配的字符。
这个算法是由高德纳和沃恩·普拉特在1974年构思,同年詹姆斯·H·莫里斯也独立地设计出该算法,最终由三人于1977年联合发表。
朴素方法的浪费
在上述朴素匹配算法的例子中, 的首字母 与后面的串 中任意一个字符都不相等。也就是说,在第①步既然已经发现前五个字符相等,就意味着 的首字符不可能与 中的第位到第位的字符相等,那么②③④⑤的比较可以说是多余的。
利用已获得信息
来看下一个例子,,。
对于开始的判断,前个字符相等,到 时失配,由于已经知道 且 与 的第位和第位字符都不相等,所以步骤②③是多余的,故可以直接向右大幅度移动 ,即 ,重新进行匹配。但是这时我们又可以发现,由于,实际上可以直接令 ,显然能匹配上,那么步骤④⑤也是多余的。
在朴素的模式匹配算法中,主串的指针 是不断地回溯的,而在上述的匹配过程中,我们发现完全可以避免不必要的回溯。这就是算法的精髓,我们可以充分利用字符串前后缀的相似性,再利用已经匹配得到的信息,避免指针的来回横跳。
算法的时间复杂度为。
定义数组
给出定义
在一般情况下, 为前 个字符组成的字符串最长相等真前后缀加一。
求数组
下面给一个计算 的例子。
j | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
---|---|---|---|---|---|---|---|
模式串T | a | b | c | a | b | x | 空 |
Next[j] | 0 | 1 | 1 | 1 | 2 | 3 | 1 |
就拿 来说,,故 。当 失配时, 的头会移动到 ,这时 和 显然能匹配上,因此我们直接将 移动到 , 即 $j=Next[j] $,称之为回退。
模板
1 | void get_Next() |
查询子串
HDU 1686 Oulipo
Problem Description
The French author Georges Perec (1936–1982) once wrote a book, La disparition, without the letter ‘e’. He was a member of the Oulipo group. A quote from the book:
Tout avait Pair normal, mais tout s’affirmait faux. Tout avait Fair normal, d’abord, puis surgissait l’inhumain, l’affolant. Il aurait voulu savoir où s’articulait l’association qui l’unissait au roman : stir son tapis, assaillant à tout instant son imagination, l’intuition d’un tabou, la vision d’un mal obscur, d’un quoi vacant, d’un non-dit : la vision, l’avision d’un oubli commandant tout, où s’abolissait la raison : tout avait l’air normal mais…
Perec would probably have scored high (or rather, low) in the following contest. People are asked to write a perhaps even meaningful text on some subject with as few occurrences of a given “word” as possible. Our task is to provide the jury with a program that counts these occurrences, in order to obtain a ranking of the competitors. These competitors often write very long texts with nonsense meaning; a sequence of consecutive 'T’s is not unusual. And they never use spaces.
So we want to quickly find out how often a word, i.e., a given string, occurs in a text. More formally: given the alphabet $\{A, B, C, …, Z\}$ and two finite strings over that alphabet, a word and a text , count the number of occurrences of in . All the consecutive characters of must exactly match consecutive characters of . Occurrences may overlap.
Input
The first line of the input file contains a single number: the number of test cases to follow. Each test case has the following format:
One line with the word W, a string over $\{A,B, C, …, Z\}$, with (here denotes the length of the string ).
One line with the text , a string over $\{A, B, C, …, Z\}$, with .
Output
For every test case in the input file, the output should contain a single number, on a single line: the number of occurrences of the word in the text .
Sample Input
3
BAPC
BAPC
AZA
AZAZAZA
VERDI
AVERDXIVYERDIAN
Sample Output
1
3
0
Translation
在字符串中找到子串,输出所有出现的位置(以第一个字符出现的位置为准)。
Idea
如上述介绍算法的模拟过程,跳过不必要的回溯。
Code
1 |
|
字符串最小循环节
POJ 1961 Period
Description
For each prefix of a given string with characters (each character has an ASCII code between and , inclusive), we want to know whether the prefix is a periodic string. That is, for each we want to know the largest (if there is one) such that the prefix of with length can be written as ,that is concatenated times, for some string . Of course, we also want to know the period .
Input
The input consists of several test cases. Each test case consists of two lines. The first one contains – the size of the string .The second line contains the string . The input file ends with a line, having the number zero on it.
Output
For each test case, output “Test case #” and the consecutive test case number on a single line; then, for each prefix with length that has a period , output the prefix size and the period separated by a single space; the prefix sizes must be in increasing order. Print a blank line after each test case.
Sample Input
3
aaa
12
aabaabaabaab
0
Sample Output
Test case #1
2 2
3 3
Test case #2
2 2
6 2
9 3
12 4
Translation
求一个字符串中前缀的最小循环节,要求输出前缀长度和它的最小循环节循环次数(次数要求至少为2)。
Idea
给出定理: 具有长度为 的循环节的充要条件是 能整除 并且 。
对于一个长度为 的前缀,该前缀的最后一个字符位于字符串的第 位,描述了字符串的相似性,表示既是子串 的前缀,同时也是子串 的后缀的最长真前缀长度 ,即,若,那么就是 的最小循环节。
进一步地,如果 能整除 ,那么 就是 的次小循环元。依次类推,我们还可以找出 所有可能的循环节。
Code
1 |
|
统计每个前缀的出现次数
HDU 3336 Count the string
Problem Description
It is well known that AekdyCoin is good at string problems as well as number theory problems. When given a string , we can write down all the non-empty prefixes of this string. For example,.The prefixes are: .For each prefix, we can count the times it matches in . So we can see that prefix matches twice, matches twice too, matches once, and matches once. Now you are asked to calculate the sum of the match times for all the prefixes. For “abab”, it is .
The answer may be very large, so output the answer mod .
Input
The first line is a single integer , indicating the number of test cases.
For each case, the first line is an integer , which is the length of string . A line follows giving the string . The characters in the strings are all lower-case letters.
Output
For each case, output only one number: the sum of the match times for all the prefixes of mod .
Sample Input
1
4
abab
Sample Output
6
Translation
给定一个字符串 所有前缀在字符串 中出现次数的总和,答案对 取模。
Idea
考虑位置 对应的 。根据定义,这意味着字符串 一个长度为 的前缀在位置 出现并以 为右端点,同时不存在一个更长的前缀满足前述定义。与此同时,更短的前缀可能以该位置为右端点。此时需要寻找下一个更小的长度为 且 的前缀,该长度的前缀同时也是一个右端点为 的后缀。因此以位置 为右端点,有长度为 的前缀,有长度为 的前缀,有长度为 的前缀,等等,直到长度变为 。
Code
1 |
|