C++ 中的 Z 算法(线性时间模式搜索算法)
Z 算法用于在字符串中查找模式的出现,时间复杂度为线性时间。假设字符串长度为 n,要搜索的模式大小为 m,则解决问题所需的时间复杂度为 O(m+n)。
Z 算法使用 Z 数组来查找模式的出现。
Z 数组
它是一个与字符串长度相同的数组。Z 数组的每个元素包含从 I 开始的字符串的最长子字符串的长度,该子字符串可以用作字符串本身的前缀。
算法
在这个算法中,我们给定一个长度为 n 的字符串 S 和一个长度为 m 的要搜索的模式 p。
我们将创建一个 Z 数组。现在,算法循环遍历字符串的所有字符,i 从 1 到 n-1。现在,我们将创建一个子字符串 s[L-R],它是一个前缀子字符串,使得 1 ≤ L ≤ I ≤ R。
现在,对于创建 i-1 的子字符串 [L, R] 的正确区间和所有直到 i-1 的 z 值。使用以下步骤计算 z[i] 和新的区间 [L, R]:
Step1: if i > R, no larger prefix-substring is possible. So, we will compute new interval bt comparing S[0] to S[i] i.e. string starting from index 0 i.e. from start with substring starting from index i. And find z[i] using z[i] = R - L + 1. Step 2: Else if, i ≤ R, [L, R] can be extended to i. For k = i-L, z[i] ≥ min(Z[k], R-i+1). Step 2.1: If, Z[k] < R-i+1, no longer prefix substring s[i] exist. Step 2.2: If Z[k] ≥ R-i+1, then there can be a longer substring. So, we will update [L, R] by changing L = i and changing R by matching from S[R+1].
此过程在一次迭代中找到所有 Z 值(仅循环一次)。
示例
显示算法实现的程序:
#include<iostream>
using namespace std;
void createZarray(string str, int Z[]){
int n = str.length();
int L, R, k;
L = R = 0;
for (int i = 1; i < n; ++i){
if (i > R){
L = R = i;
while (R<n && str[R-L] == str[R])
R++;
Z[i] = R-L;
R--;
} else {
k = i-L;
if (Z[k] < R-i+1)
Z[i] = Z[k];
else {
L = i;
while (R<n && str[R-L] == str[R])
R++;
Z[i] = R-L;
R--;
}
}
}
}
void zAlgorithm(string text, string pattern){
string str = pattern+"$"+text;
int len = str.length();
int Z[len];
createZarray(str, Z);
for (int i = 0; i < len; ++i){
if (Z[i] == pattern.length())
cout<<(i-pattern.length()-1)<<"\t";
}
}
int main(){
string str = "Hello! Welcome To tutorials Point programming tutorial";
string pattern = "tutorial";
cout<<"The patter ' "<<pattern<<" ' is found in the string '"<<str<<" ' at index \t";
zAlgorithm(str, pattern);
return 0;
}输出
The patter ' tutorial ' is found in the string 'Hello! Welcome To tutorials Point programming tutorial ' at index 18 46
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP