题目
首先读进一个包含10000个英文单词的文件,然后接受用户输入的模式字符串,开始匹配文件中该模式串出现了多少次。
实现
使用KMP实现,先根据模式串生成next数组,然后在对每一行文本进行kmp匹配。将结果打印出来
代码
#include<iostream>
#include<fstream>
#include<string>
#include<string.h>
using namespace std;
string pattern;
void nextAry(int* next){
int pLen =pattern.length();
int i=0,j=-1;
next[i]=j; //i is increment all the way
while(i<pLen){
if(j==-1||pattern.at(i)==pattern.at(j)){
i++;
j++;
next[i]=j;
}else{
j = next[j];
}
}
}
void KMP(string text,int* next)
{
int pLen =pattern.length();
int tPos = 0,pPos=0,tLen = text.length();
while(tPos<tLen&&pPos<pLen){
if(pPos==-1||text.at(tPos)==pattern.at(pPos)){
tPos++;
pPos++;
if(pPos>=pLen){
cout<<text.substr(tPos-pLen-1,pLen+2)<<endl;
cout<<text<<endl;
return;
}
}else{
pPos = next[pPos];
}
}
}
void readTxt(string file,int* next)
{
ifstream infile;
infile.open(file.data()); //将文件流对象与文件连接起来
string s;
while(getline(infile,s))
{
KMP(s,next);
}
infile.close(); //关闭文件输入流
}
int main(){
cout<<"Please Enter the pattern string:";
cin>>pattern;
int* next= new int[pattern.length()+1];
nextAry(next);
readTxt("word.txt",next);
delete next;
}