1 条题解

  • 0
    @ 2025-3-24 17:36:09
    #include <iostream>
    #include <string>
    using namespace std;
    
    // 函数声明
    void buildNext(const string &B, int *next);
    int kmp(const string &A, const string &B, int *next);
    
    int main() {
        string A, B;
        cin >> A >> B;
    
        int lenB = B.length();
        int next[lenB]; // 部分匹配表
        buildNext(B, next);
    
        int count = kmp(A, B, next);
        cout << count << endl;
    
        return 0;
    }
    
    // 构建部分匹配表
    void buildNext(const string &B, int *next) {
        int lenB = B.length();
        next[0] = 0; // 初始化
        int j = 0; // 前缀末尾
    
        for (int i = 1; i < lenB; i++) { // 遍历 B 的每个字符
            while (j > 0 && B[i] != B[j]) {
                j = next[j - 1]; // 回退
            }
    
            if (B[i] == B[j]) {
                j++;
            }
    
            next[i] = j; // 更新 next 数组
        }
    }
    
    // KMP 匹配算法
    int kmp(const string &A, const string &B, int *next) {
        int lenA = A.length();
        int lenB = B.length();
        int j = 0; // B 的当前匹配位置
        int count = 0; // 计数器
    
        for (int i = 0; i < lenA; i++) { // 遍历 A 的每个字符
            while (j > 0 && A[i] != B[j]) {
                j = next[j - 1]; // 回退
            }
    
            if (A[i] == B[j]) {
                j++;
            }
    
            if (j == lenB) { // 找到一个匹配
                count++;
                j = next[j - 1]; // 更新 j 为 next[j-1],继续寻找下一个匹配
            }
        }
    
        return count;
    }
    
    • 1

    信息

    ID
    911
    时间
    1000ms
    内存
    512MiB
    难度
    (无)
    标签
    (无)
    递交数
    0
    已通过
    0
    上传者