首页 > 编程语言 > 详细

C++ KMP文本匹配

时间:2019-11-20 20:55:37      阅读:92      评论:0      收藏:0      [点我收藏+]

代码如下:

环境为VC

#include <iostream>
#include <algorithm>
#include <string>
#include <map>
#include <vector>
#include <cstring>
#include <utility>
#include <fstream>

using namespace std;

int* getNext(string p)
{
    int* next = new int[p.length()];
    next[0] = -1;       //第一个字符不匹配, i++,j++
    int j = 0;
    int k = -1;
    while (j < (int)p.length() - 1)
    {
        if (k == -1 || p[j] == p[k])
        {
            j++;
            k++;
            next[j] = k;
        }
        else
        {
            k = next[k];
        }
    }
    return next;
}

// KMP算法
int KMPMatcher(string T, string p)
{
    int i = 0;
    int j = 0;
    int* next = getNext(T);
    while (i < (int)T.length() && j < (int)p.length())
    {
        if (j == -1 || T[i] == p[j])
        {
            i++;
            j++;
        }
        else
        {
            j = next[j];
        }
    }
    if (j == (int)p.length())
    {
        return i - j;
    }
    return -1;
}

//分割字符串
vector<string> split(const string& str, const string& delim) {
    vector<string> res;
    if ("" == str) return res;
    //先将要切割的字符串从string类型转换为char*类型
    char * strs = new char[str.length() + 1];
    strcpy(strs, str.c_str());

    char * d = new char[delim.length() + 1];
    strcpy(d, delim.c_str());

    char *p = strtok(strs, d);
    while (p) {
        string s = p;  //分割得到的字符串转换为string类型
        res.push_back(s); //存入结果数组
        p = strtok(NULL, d);
    }
    return res;
}

int main() //生成通过关键字生成肢体动作指令
{   
    //关键词对话动作映射
    map<string, int> myMap;
    ifstream ous("dialog_action.txt");
    while (!ous.eof()) {
        string temp;
        ous >> temp;
        vector<string> tempstr = split(temp, "=");
        string key = tempstr[0].c_str();
        string value_1 = tempstr[1].c_str();
        int value = stoi(value_1); //string转int
        myMap.insert(make_pair(key, value)); //将字符串转换为键值对
    }

    map<string, int>::iterator it;
    
    for (it = myMap.begin(); it != myMap.end(); it++)
    {
        string T = sCmd;
                cout << "enter command:" << flush;
        getline(cin, sCmd);
        string p = it->first;
        if (KMPMatcher(T, p) >= 0) {
            it != myMap.end(); //跳出循环
            //cout << myMap[p] << endl;
            return myMap[p];
            break;
        }
    }
}

C++ KMP文本匹配

原文:https://www.cnblogs.com/spmt/p/11900228.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!