zoukankan      html  css  js  c++  java
  • KMP字符串查找算法

    #include <iostream>
    #include <windows.h>
    using namespace std;
    
    void get_next(char *str,int *num)
    {
        int idFront = 0;
        int len = strlen(str);
        int amount = 1;
        int flag = 0;//相等时一直往下循环
        int flag2 = 0;//标记是否在循环过程中不匹配,如果在循环过程中不匹配,则要防止跳过这个数
    
        for(int i = 2;i<len;i++)
        {
            do
            {
                if(str[i-1] == str[idFront])
                {
                    flag2 = 1;
                    num[i] = ++amount;
                    flag = 1;//保证相等就会循环一直循环到不等
                    i++;
                    idFront++;
                }
                else
                {
                    if(flag2 == 1)//保证在相等循环时最后一个不匹配,然后再与第0个进行比较,避免外层for循环跳过这个不匹配的数
                    {
                        i--;
                    }
                    flag2 = 0;
                    flag = 0;
                    idFront = 0;
                    amount = 1;
                }
            }while(flag == 1);
        }
    }
    
    void find(char *str,char *substr)
    {
        int *next = new int[strlen(substr)];
        for(int p=0;p<strlen(substr);p++)
        {
            next[p] = 1;
        }
        next[0] = 0;
    
        get_next(substr,next);
    
        int i=0;//i不会回溯
        int j=0;
        int count = 1;
        while(i<strlen(str) && j < strlen(substr))
        {
            cout << "" << count++ << "次比较,i = " << i << "   j = " << j ;
            
            if(str[i] == substr[j])
            {
                cout << "      相等  " << endl;
                system("pause");
                i++;
                j++;
            }
            else
            {
                cout << "      不相等  " << endl;
                system("pause");
                if(j>0)
                {
                    j = next[j] - 1;//下一次i与j比较的位置,可以在纸上画出来然后找出关系
                }
                else
                {
                    j = 0;
                    i++;
                }
            }
        }
    
        int len = strlen(substr);
        if(j == len)
        {
            cout << "找到,位置为" << i-strlen(substr) << endl;
        }
        else
        {
            cout << "没找到" << endl;
        }
    }
    
    void main()
    {
        char *str = "abcdabcdabcdabceabcdabcabcdadewerwq";
        char *substr = "abcdabce";
        cout << str << endl;
        cout << substr << endl;
        find(str,substr);
    }
  • 相关阅读:
    鲜牛奶与纯牛奶的区别 All In One
    Rough Notation Animation All In One
    java基础编程String及相关
    JDBC1
    java基础数据类型
    java基础编程
    JDBC3
    MYSQL1
    JDBC2
    JSP和Servlet的相同点和不同点,他们之间的联系
  • 原文地址:https://www.cnblogs.com/xiaochi/p/5055791.html
Copyright © 2011-2022 走看看