c++实现KMP算法

题目

首先读进一个包含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;



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值