请教一个有关字符串的算法问题

see22 2005-01-02 12:26:50
给定一个字符串,如何在上万个字符串中搜索出匹配的,
需要用C语言实现,有没有最优算法. 谢谢,祝大家新年快乐!!!
...全文
276 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
see22 2005-01-03
  • 打赏
  • 举报
回复
上万个字符串的存储方式是由我自己决定的,
需要的是最快的算法
hewittlee 2005-01-03
  • 打赏
  • 举报
回复
kmp!
fire_zyn 2005-01-03
  • 打赏
  • 举报
回复
我想KMP算法应该是很好的选择。
多数数据结构书上都有描述。

数学学得好,可以阅读《计算机程序设计艺术(卷3)》
bluewinwind 2005-01-03
  • 打赏
  • 举报
回复
顶一下,具体的算法和存储的初始状态有关,
Lethe_1 2005-01-03
  • 打赏
  • 举报
回复
你说的匹配是模式匹配么?
oo 2005-01-02
  • 打赏
  • 举报
回复
所谓最优算法,跟你的需求有关的:
看你时间和空间怎么平衡。
yjy1001 2005-01-02
  • 打赏
  • 举报
回复
mark下
sharkhuang 2005-01-02
  • 打赏
  • 举报
回复
关键看这成千上万个字符串怎么存储的。
xuelong_zl 2005-01-02
  • 打赏
  • 举报
回复
mark
avalonBBS 2005-01-02
  • 打赏
  • 举报
回复
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[i]!=T[j+1]&& j>=0 )
j=next[j] ; //递推计算
if(T[i]==T[j+1])next[i]=j+1;
else next[i]=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;
}


goodluckyxl 2005-01-02
  • 打赏
  • 举报
回复
我一直是使用复杂度为N的匹配方式
我自己没有想过更好的
str1 str2
依次往前匹配,在m长度处匹配失败str2+m开始再和str1比较
直到结束
nwpulipeng 2005-01-02
  • 打赏
  • 举报
回复
要自己动手写吗?KMP是什么算法呀?关注并混点分
fatalerror99 2005-01-02
  • 打赏
  • 举报
回复
算法和数据结构是密不可分的。

这和那上万个字符串的存储结构,是否排序以及搜索次数都有很大关系。

如果需要多次搜索的话,建议先对字符串进行排序,可以数量级倍提高搜索效率。
Army123 2005-01-02
  • 打赏
  • 举报
回复
有个KMP算法,很不错的!

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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