zoukankan      html  css  js  c++  java
  • 数据结构与算法参考答案(第六周)

    一、复习与实现KMP算法,要求有运行测试截图。

    答:

    KMP是实现字符串匹配的较好的算法。本算法的关键在于求出next数组,然后在调用时利用next数组可以使T往后移动得更多,从而提高匹配的效率。

    该算法利用C++编程语言实现的代码如下:

    //利用C++实现KMP算法
    #include <iostream>
    #include <string>
    using namespace std;
    int Index_KMP(string S, string T, int pos, int next[]) {
         // 利用模式串T的next函数求T在主串S中的第pos个
         //字符之后的位置的KMP算法。其中,T非空,
         // 1≤pos≤StrLength(S)
        int i = pos;   
        int j = 1;
        while (i <= S.size() && j <= T.size()) {  //0下标存储字符串长度
            if (j == 0 || S[i - 1] == T[j - 1]) { ++i;  ++j; }  // 继续比较后继字符
                else  j = next[j];         // 模式串向右移动
            }
        if (j > T.size())  return  i-T.size();    // 匹配成功
        else return 0;
    } // Index_KMP
    
    void get_next(string T, int next[]) {
         // 求模式串T的next函数值并存入数组next
         int i = 1;   
         next[1] = 0;   
         int j = 0;
         
         while (i < T.size()) {
            if (j == 0 || T[i - 1] == T[j - 1])
            {
                ++i;  
                ++j; 
                next[i] = j; 
            }
            else  j = next[j];
        }
    } // get_next
    
    int main () {
        int next[100];
        string S, T;
        while(1) {
            cout <<  "请输入匹配串:";
            cin >> S;       /*测试样例:S = "fhwuefihfwabaabcaccaahadc"; S = "fhwuefihfwaba"; T = "abaabcacca"; */
            cout << "请输入模式串:";
            cin >> T;
            get_next(T, next);
            cout << "匹配串为:" << S << endl;
            cout << "模式串为:" << T << endl;
            cout << "next数组为:";
            for(int i = 1; i <= T.size(); ++i) {
                cout << next[i] << " ";    
            }
            cout << endl;
            if(Index_KMP(S, T, 0, next)) {
                cout << "匹配成功:匹配串中第" << Index_KMP(S, T, 0, next) << "个字符为模式串开始" << endl;
            }
            else{
                cout << "匹配失败!未找到模式串!" << endl;
            }    
            cout << endl;
        }
    }
    

    代码运行结果如下:

     

    1 KMP算法运行结果示意图

    作者:LightAc
    出处:https://www.cnblogs.com/lightac/
    联系:
    Email: dzz@stu.ouc.edu.cn
    QQ: 1171613053
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    java.io.EOFException ValueOperations.increment()操作后,获取值时有的bug
    使用maven profile指定配置文件打包适用多环境
    关于3Q大战和反垄断
    在ECUG2010上的演讲稿
    让Windows7在启动时自动挂载虚拟磁盘
    也谈并行计算(一)C#版的Parallel.For实现
    给.NET的string类添加一个命令行参数分解的扩展
    顺序表 code
    很高兴开始博客之旅 code
    (原)前端知识杂烩(css系列)
  • 原文地址:https://www.cnblogs.com/lightac/p/12832484.html
Copyright © 2011-2022 走看看