KMP matching algorithm and application (code)

Reference understanding: https://oi-wiki.org/string/kmp/
https://blog.csdn.net/daaikuaichuan/article/details/80719203

Construct next array

void get_next(int next_[], char str[]) {
    
    
    int len = strlen(str);
    next_[0] = 0;
    for (int i = 1; i < len; i++) {
    
    
        /*j表示上一个匹配的长度, j - 1就是j长度的前缀的末尾下标*/
        int j = next_[i - 1];
        /*如果不匹配, j == 0 或 不匹配时退出循环*/
        while (j > 0 && str[i] != str[j]) j = next_[j - 1];  //向前回溯查找
        if (str[i] == str[j]) j++;
        next_[i] = j;
    }
}

KMP algorithm application

Find a substring in a string

vector<int> KMP(char str[], char str1[], int next_[]) {
    
    
    vector<int> vec;
    int len = strlen(str);
    int j = 0;  //初始
    for (int i = 0; i < len; i++) {
    
    
        if (str[i] == str1[j]) {
    
    
            j++;
        } else if (j) {
    
            // 如果j == 0, 且不匹配直接跳过
            j = next_[j - 1];  //回溯, 注意不是 j = next_[j] - 1
            i--;
        }

        if (j == strlen(str1)) {
    
           //匹配成功
            vec.push_back(i - j + 1);  //记录匹配位置
            j = 0;                     //重新匹配余下的字符串
        }
    }
    return vec;
}

The period of the string

Count the number of occurrences of each prefix

PTA good suffix: https://blog.csdn.net/qq_45349225/article/details/109644783

The number of intrinsically different substrings in a string

String compression

Construct an automaton based on the prefix function

Related questions

Guess you like

Origin blog.csdn.net/qq_45349225/article/details/109643916