模式匹配

yezeguo 2008-05-01 08:22:37
请大家帮忙写一个模式匹配程序,用到KMP算法,求模式串在主串出现的次数,要考虑到时间复杂度,
模式串最长为10000,主串为1000000,谢谢了!!!
...全文
136 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
hujinyong199 2008-05-02
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

void _GetLine(string &str, char delim='\n')
{
char Text[1000000];
Text[0]='\0';

cin.getline(Text,1000000,delim);
str=Text;
}


int is_matched(const string& src, const string& dst)
{
int count = 0;
const char *p = find(src.begin(), src.end(), dst[0]);
while(p != src.end() )
{
int i = 0;
while(*p == dst[i])
{
++i;
++p;
}
if(i == dst.size() )
++count;

p = find(p, src.end(), dst[0]);
}

return count;
}

int main()
{
string s1, s2;
cout<<"请输入被查找串:\n";
_GetLine(s1);
cout<<"请输入子串:\n";
_GetLine(s2);
int cnt = is_matched(s1, s2);
cout<<"子串在被查找串中出现了"<<cnt<<"次\n";
return 0;
}



zsxcn 2008-05-02
  • 打赏
  • 举报
回复
mark
yezeguo 2008-05-01
  • 打赏
  • 举报
回复
知道书上有啊
看过,编过程序,结果错误
guocai_yao 2008-05-01
  • 打赏
  • 举报
回复
kmp算法还没看到呢
bitxinhai 2008-05-01
  • 打赏
  • 举报
回复
数据结构书上一般都有的,
找本书自己解析一下
yezeguo 2008-05-01
  • 打赏
  • 举报
回复
运行错误挺多的,33个多
guzhilei1986 2008-05-01
  • 打赏
  • 举报
回复
string可以存下你的数据。不用担心没有问题。
guzhilei1986 2008-05-01
  • 打赏
  • 举报
回复
摘自百度知道
KMP算法查找串S中含串P的个数count
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;

inline void NEXT(const string& T,vector<int>& next)
{
//按模式串生成vector,next(T.size())
next[0]=-1;
for(int i=1;i<T.size();i++ ){
int j=next[i-1];
while(T!=T[j+1]&& j>=0 )
j=next[j] ; //递推计算
if(T==T[j+1])next=j+1;
else next=0; //
}
}
inline string::size_type COUNT_KMP(const string& S,
const string& T)
{
//利用模式串T的next函数求T在主串S中的个数count的KMP算法
//其中T非空,
vector<int> next(T.size());
NEXT(T,next);
string::size_type index,count=0;
for(index=0;index<S.size();++index){
int pos=0;
string::size_type iter=index;
while(pos<T.size() && iter<S.size()){
if(S[iter]==T[pos]){
++iter;++pos;
}
else{
if(pos==0)++iter;
else pos=next[pos-1]+1;
}
}//while end
if(pos==T.size()&&(iter-index)==T.size())++count;
} //for end
return count;
}
int main(int argc, char *argv[])
{
string S="abaabcacabaabcacabaabcacabaabcacabaabcac";
string T="ab";
string::size_type count=COUNT_KMP(S,T);
cout<<count<<endl;

system("PAUSE");
return 0;
}

64,652

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧