zoukankan      html  css  js  c++  java
  • KMP

    说明:给出文本串和模式串,找出模式串在文本串中出现的位置

    解法:

    1、暴力解法(BF)

    int BF(string s, string t, int lens, int lent) {
        int i = 0, j = 0;
        while (i < lens && j < lent) {
            if(s[i] == t[j]) {
                i++;
                j++;
            } 
            else {
                i = i + j - 1;
                j = 0;
            }
        }
        if (j == lent) {
            return i - j;
        }
        else return -1;
    }

    2、KMP解法

    说明:i不回溯,移动模式串

    右移位数 = 失配所在位置 - 失配对应的next[]值

    (next[j] = k :j之前的字符串有最大长度k的相同前缀后缀)

    void get_next() {
        int i = 0, j = -1;
        next[0] = -1;
        while (i < lent) {
            if (j == -1 || t[i] == t[j]) next[++i] = ++j;
            else j = next[j];
        }
    }
    void KMP() {
        int i = 0, j = 0;
        while (i < lens) {
            if (j == -1 || s[i] == t[j]) {
                i++;
                j++;
            }
            else j = next[j];
            if (j == lent) {
                cout << i - lent + 1;
                j = next[j];
            }
        }
    }
  • 相关阅读:
    The nineteenth day
    The eighteen day
    弱读下
    弱读上
    失爆 爆破音
    连读
    The seventeenth day
    The sixteenth day
    React 官方脚手架 create-react-app快速生成新项目
    pc端引入微信公众号文章
  • 原文地址:https://www.cnblogs.com/iwomeng/p/13964069.html
Copyright © 2011-2022 走看看