kmp求条
  • 板块灌水区
  • 楼主jzy_CSPJ_AK
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/11/22 18:19
  • 上次更新2024/11/22 20:13:54
查看原帖
kmp求条
1034698
jzy_CSPJ_AK楼主2024/11/22 18:19
#include <bits/stdc++.h>
using namespace std;
string s1, s2;
vector<int> nxtval;
void get_nxtval(string s1, vector<int>& nxtval) {
    nxtval.resize((int)(s1.length())), nxtval[0] = -1;
    int i = 0, j = 0, lens = s1.length();
    while (i < lens && j < lens) {
        if (j == -1 || s1[i] == 0) {
            ++i, ++j;
            if (s1[i] == s1[j])
                nxtval[i] = nxtval[j];
            else
                nxtval[i] = j;
        } else
            j = nxtval[j];
    }
}
int KMP(string s1, string s2, vector<int> nxtval) {
    int i = 0, j = -1, lens = (int)(s1.size());
    while (i < lens && j < lens) {
        if (j == -1 || s1[i] == s2[j]) {
            ++i, ++j;
            if (j == s2.length()) {
                return i - j + 1;
            }
        } else
            j = nxtval[j];
    }
}
int main() {
    ios::sync_with_stdio(false);
    cin >> s1 >> s2;
    get_nxtval(s1, nxtval);
    cout << KMP(s1, s2, nxtval);
    return 0;
}
2024/11/22 18:19
加载中...