Skip to content

Instantly share code, notes, and snippets.

@heno239
Last active July 7, 2020 04:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heno239/50c316550583e8bdd93936ca4009c9df to your computer and use it in GitHub Desktop.
Save heno239/50c316550583e8bdd93936ca4009c9df to your computer and use it in GitHub Desktop.
online Z algorithm
struct online_Z_algorithm {
private:
string s;
vector<int> a;
set<int> cur;
vector<vector<int>> delete_memo;
public:
online_Z_algorithm() { delete_memo.push_back({}); };
void del(int loc, int len) {
cur.erase(loc);
delete_memo[len].push_back(loc);
a[loc] = len - loc - 1;
}
//末尾に文字cを挿入する
void add(char c) {
s.push_back(c);
int len = s.size();
a.push_back(0);
delete_memo.push_back({});
if (len == 1)return;
if (s[0] == c)cur.insert(len - 1);
while (cur.size()) {
int left = *cur.begin();
if (s[len - left - 1] == s.back())break;
else {
del(left, len);
}
}
if (cur.size()) {
int pre = *cur.begin();
for (int past : delete_memo[len-pre]) {
del(past + pre,len);
}
}
}
//loc番目以降の文字列と元の文字列の最長共通接頭辞を求める
int query(int loc) {
if (loc == 0)return s.size();
if (cur.count(loc))return s.size() - loc;
else return a[loc];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment