2019/10/18日修改
经过了约一年的学习,对strstr的实现方法有了更多更深层次的了解,回想起来当年写的博客真的是思路简单而且笨拙,然而那时候写暴力匹配算法的我还是很可爱呢www,想了想还是把这篇留下来吧,顺便贴一下现在用C++写的暴力匹配算法:
#include <iostream>
using namespace std;
int NaiveStrMatching(const string& T, const string& P)
{
int p = 0;
int t = 0;
int plen = P.length();
int tlen = T.length();
if (tlen < plen)
return -1;
while (p < plen && t < tlen)
{
if (T[t] == P[p])
{
p++;
t++;
}
else
{
t = t - p + 1;
p = 0;
}
}
if (p == plen)
return t - p;
else
return -1;
}
int main()
{
string strT = "BBC ABCDAB ABCDABCDABDE";
string strP = "ABCDABD";
int res = NaiveStrMatching(strT, strP);
cout << res << endl;
return 0;
}
2018/12/26 原答案:
- 本文汇总了全网各路大佬的经验(其实没几篇),努力打造最强strstr模拟技术贴(大误)
- 不说废话直接看实现思路:
定义两个指针*p1,*p2指向两个字符串,开始比较;
若*p1==*p2,则p1++,p2++,两个指针同时向后移动,比较之后的字符;
若*p1!= *p2,则*p2