70分求救
查看原帖
70分求救
1185542
restaier楼主2024/10/29 10:16
#include<bits/stdc++.h>
using namespace std;

vector<int> nextArray(string s) {
    int m = s.length();
    vector<int> next(m + 1, 0);
    next[0] = -1;
    next[1] = 0;
    int cn = 0, i = 2;//cn是起始位置,i是当前位置
    while(i <= m) { 
        if(s[i - 1] == s[cn]) {
            next[i++] = ++cn;
        }
        else if(cn > 0) {
            cn = next[cn];
        }
        else {
            next[i++] = 0;
        }
    }
    return next;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    string s1, s2;
    cin >> s1 >> s2;
    vector<int> next = nextArray(s2);
    int i = 0, j = 0;
    vector<int> ans;
    while(i < s1.length()) {
        if(s1[i] == s2[j]) {
            i++;
            j++;
            if(j == s2.length()) {
                ans.push_back(i - j+1);
                j = next[j];  // 修正为 `j = next[j]`
            }
        }
        else if(j > 0) {
            j = next[j];
        }
        else {
            i++;
        }
    }
    if(ans.empty()) cout << "-1" << endl;
    else for(auto index : ans) cout << index <<endl;
    for(int i=1;i<=s2.length();i++){
		cout<<next[i]<<' ';
	}
}
2024/10/29 10:16
加载中...