Two Matches Gone Missing
To find s inside t, KMP concatenates them with a separator that appears in neither string, computes the prefix function of the whole thing, and reports a match wherever the value equals |s|. A reviewer removes the separator to save memory:
vector<int> pi = prefix_function(s + t); // separator dropped
for (int i = s.size(); i < pi.size(); i++)
if (pi[i] == (int)s.size())
cout << i - 2 * s.size() + 1 << "\n"; // occurrence in t
Run it with s = "aa" and t = "aaa". The pattern really does occur in t, at positions 0 and 1. What does the loop print?
Sign in to answer questions and track your progress
Sign In