PTA good suffix (10 points) (string matching + prefix function)

7-8 good suffix (10 points)

We call the suffix of a string a good suffix if it meets the following conditions:

(1) It appears at least 2 times in the string;

(2) The longest one that satisfies the condition (1).

Please write a program to calculate the good suffix length of a string, and note that a string cannot be called its own suffix.

Input and output description

Input format:

The input is a string containing no more than 10^​5 letters.

Output format:

The output is an integer, which represents a good suffix length of the input string.

Sample

Input example 1:

xacbacba

Output example 1:

4

Input example 2:

yxxabacaba

Output example 2:

3

Input example 3:

abc

Output sample 3:

0

Problem solving

First look at the definition of the prefix function:
Insert picture description here
according to the definition, next[i] = k; k is the length of the longest same true prefix and suffix in the substring with i as the end subscript. Therefore, this question first reverses the string, and then asks The biggest next[i] problem

Code

#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 1e5 + 2;
char str[maxn];
int next_[maxn];
int ans;

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;
        ans = max(ans, j);
    }
}

int main() {
    
    
    scanf("%s", str);
    reverse(str, str + strlen(str));
    get_next(next_, str);
    // for (int i = 0; i < strlen(str); i++) {
    
    
    //     printf("%d ", next_[i]);
    // }
    printf("%d\n", ans);

    system("pause");
    return 0;
}

Guess you like

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