From aad9d251b1011823e523772cd87406229ffe121d Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Mon, 25 Apr 2022 11:36:14 +0800 Subject: [PATCH] =?UTF-8?q?#165.=20=E3=80=90=E6=A8=A1=E6=9D=BF=E3=80=91KMP?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E5=8C=B9=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://sjzezoj.com/submission/52812 --- S2OJ/165/165.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 S2OJ/165/165.cpp diff --git a/S2OJ/165/165.cpp b/S2OJ/165/165.cpp new file mode 100644 index 00000000..4b0ae067 --- /dev/null +++ b/S2OJ/165/165.cpp @@ -0,0 +1,28 @@ +#include +#include + +using std::cin; +using std::cout; +const char endl = '\n'; + +int nxt[1000005]; +std::string s, p; + +int main() { + cin >> s >> p; + nxt[0] = -1; + for (int i = 1, j = -1; i < p.size(); i++) { + while (j >= 0 && p[j + 1] != p[i]) j = nxt[j]; + if (p[j + 1] == p[i]) j++; + nxt[i] = j; + } + for (int i = 0, j = -1; i < s.size(); i++) { + while (j != -1 && s[i] != p[j + 1]) j = nxt[j]; + if (s[i] == p[j + 1]) j++; + if (j == p.size() - 1) { + cout << i - j + 1 << endl; + j = nxt[j]; + } + } + return 0; +}