数据结构–字符串的朴素模式匹配算法
主串:
\color{purple}主串:
主串:
‘嘿嘿嘿红红火火恍恍惚惚嗨皮开森猴开森
笑出猪叫
\color{red}笑出猪叫
笑出猪叫哈哈哈哈嗨森哈哈哈哈哈哈嗝’
模式串:
\color{purple}模式串:
模式串:
‘笑出猪叫’
\color{red}‘笑出猪叫’
‘笑出猪叫’
子串
−
−
主串的一部分,一定存在
\color{pink}子串--主串的一部分,一定存在
子串−−主串的一部分,一定存在
模式串
−
−
不一定能在主串中找到
\color{pink}模式串--不一定能在主串中找到
模式串−−不一定能在主串中找到
两种模式匹配算法
![](https://img-blog.csdnimg.cn/6ce8da0a0250465e87cc91ae218be5d1.png)
朴素模式匹配算法
![](https://img-blog.csdnimg.cn/b27672a8a6244f9d9bc9291129cb28bd.png)
![](https://img-blog.csdnimg.cn/50ba597adeae4b3d89e496b1480f32a1.png)
… …
![](https://img-blog.csdnimg.cn/7fbbdd412ea04cd9992df7a8c446ef6a.png)
… …
![](https://img-blog.csdnimg.cn/db72817fb83140fa97aafc0f444cc8c7.png)
主串长度为n,模式串长度为m
最多对比
n
−
m
+
1
个子串
\color{red}最多对比n-m+1个子串
最多对比n−m+1个子串
朴素模式匹配算法︰将主串中
所有长度为
m
的子串
\color{red}所有长度为m的子串
所有长度为m的子串依次与模式串对比,直到找到一个完全匹配的子串,或所有的子串都不匹配为止。
![](https://img-blog.csdnimg.cn/e416ad3ae2514150a7d26d2940de6ae4.png)
typedef struct
{
char ch[15];
int length;
}SString;
int Index(SString S, SString T)
{
int i = 1, j = 1;
while (i <= S.length && j <= T.length)
{
if (S.ch[i] == T.ch[j]) i++, j++;
else i = i - j + 2, j = 1;
}
if (j > T.length)
return i - T.length;
else
return 0;
}
时间复杂度
最坏时间复杂度= O(nm)
![](https://img-blog.csdnimg.cn/0f3bd159d3b54cfcbefcb60ad50d3bf9.png)
最坏的情况,每个子串都要对比
m
m
m 个字符,共
n
−
m
+
1
n-m+1
n−m+1 个子串,复杂度=
O
(
(
n
−
m
+
1
)
m
)
=
O
(
n
m
)
O((n-m+1)m)= O(nm)
O((n−m+1)m)=O(nm)
注:很多时候,n >> m
知识点回顾与重要考点
![](https://img-blog.csdnimg.cn/5dc4cd9fb4914a74bc9f0ceced291e5f.png)