From c3ea7e194a853e5b07bd6b17face9fd5b1d91743 Mon Sep 17 00:00:00 2001 From: subcrip Date: Sun, 24 Nov 2024 17:18:56 +0000 Subject: [PATCH] Add string/manacher.cc Signed-off-by: subcrip --- string/manacher.cc | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 string/manacher.cc diff --git a/string/manacher.cc b/string/manacher.cc new file mode 100644 index 0000000..d3f2741 --- /dev/null +++ b/string/manacher.cc @@ -0,0 +1,28 @@ +template +vector manacher(const vector& s, const T& never) { + vector t = { never }; + for (auto&& c : s) { + t.emplace_back(c); + t.emplace_back(never); + } + int n = t.size(); + vector r(n); + for (int i = 0, j = 0; i < n; ++i) { + if (2 * j - i >= 0 && j + r[j] > i) { + r[i] = min(r[2 * j - i], j + r[j] - i); + } + while (i - r[i] >= 0 && i + r[i] < n && t[i - r[i]] == t[i + r[i]]) { + r[i] += 1; + } + if (i + r[i] > j + r[j]) { + j = i; + } + } + for (int i = 0; i < n; i += 2) { + r[i] = (r[i] - 1) / 2; + } + for (int i = 1; i < n; i += 2) { + r[i] /= 2; + } + return r; +}