神秘 2way 字符串匹配算法

· · 个人记录

网上能搜到对这个算法的描述都非常抽象且高度省略所以先贺了个代码,等哪天看懂了说不定这里会出现一篇讲解。

简单说一下优势吧:时间线性的前提下额外空间 O(1),据说 strstr 也是用这个写的。

题目。

#include <bits/stdc++.h>
using namespace std;
vector<int> strmatch(string s, string t) {
  static auto maxsuf = [](string& s, auto cmp) {
    int ret = -1, ans = 1, i = 0, j = 1, n = s.length();
    while (i + j < n) {
      char x = s[i + j], y = s[ret + j];
      if (cmp(x, y))
        ans = (i += j) - ret, j = 1;
      else if (cmp(y, x))
        ret = i++, j = ans = 1;
      else
        j == ans && (i += j, j = 0), ++j;
    }
    return make_pair(ret, ans);
  };
  auto [lps, per] = max(maxsuf(s, less<char>()), maxsuf(s, greater<char>()));
  int pos = -1, i = 0, m = s.length(), n = t.length();
  vector<int> ret;
  bool b = memcmp(s.data(), s.data() + per, lps + 1);
  if (b) per = max(lps + 1, m - lps - 1) + 1;
  while (i <= n - m) {
    int j = max(pos, lps + 1);
    while (j < m && s[j] == t[i + j]) ++j;
    if (j >= m) {
      j = lps;
      while (j > pos && s[j] == t[i + j]) --j;
      if (j <= pos) ret.push_back(i);
      i += per, !b && (pos = m - per - 1);
    } else
      i += j - lps, pos = -1;
  }
  return ret;
}
signed main() {
  cin.tie(nullptr)->sync_with_stdio(false);
  int T;
  for (cin >> T; T; --T) {
    string s, t;
    cin >> s >> t;
    auto ret = strmatch(t, s);
    if (ret.empty())
      cout << "Not Found";
    else {
      cout << ret.size() << '\n';
      for (int x : ret) cout << x + 1 << ' ';
    }
    cout << "\n\n";
  }
  return cout << flush, 0;
}