Loading

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];
        }
    }
}

 

posted @ 2020-11-12 15:13  qinuna  阅读(148)  评论(0编辑  收藏  举报