全WA求调玄关
查看原帖
全WA求调玄关
1198506
wo488楼主2024/10/15 20:49
#include<bits/stdc++.h>
using namespace std;
int build_next(string patt,vector<int>&next) {
    next.push_back(0);
    int prefix_len = 0;
    int i = 1;
    int j;
    while (i < patt.size()) {
        if (patt[prefix_len] == patt[i]) {
            prefix_len += 1;
            next.push_back(prefix_len);
            i += 1;

        }
        else {
            if (prefix_len == 0) {
                next.push_back(0);
                i += 1;
            }
            else
                prefix_len = next[prefix_len - 1];
        }
        

    }
    
    return 0;
}
int kmp_search(string ss, string patt,vector<int>next){
    int i = 0;
    int j = 0;
    while (i < ss.size()) {
        if (ss[i] == patt[j]) {
            i++;
            j++;
        }
        else
        {
            if (j > 0)
                j = next[j - 1];
            else
                i += 1;
        }


        if (j == patt.size()) {
            return i - j;
        }
       
    }
    return -1;
    
}

int main() {
    string s1;
    string s2;
    cin >> s1;
    cin >> s2;
    int x, y, z;
    int t = 0;
    vector<int>next;
    build_next(s2, next);
    x = kmp_search(s1, s2,next);
    if(x>=0)
    printf("%d\n", x+1);
    while (t + s2.size() <= s1.size()) {
        x = kmp_search(s1.substr(t, s1.size() - t), s2, next);
        if (x >= 0) {
            t += s2.size();
        }
        else {
            t++;
        }
        if (x >= 0) {
           printf("%d\n", x + t);
        
        }
        
    }
    for (y = 0; y < s2.size(); y++) {
        printf("%d ", next[y]);
    }
    printf("\n");


}
2024/10/15 20:49
加载中...