fork(10) download
  1. #include <string>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. int main() {
  8. string sample = "aabaa";
  9. string text = "aabaabaaaabaabaaab";
  10. vector<size_t> prefix(sample.length());
  11.  
  12. size_t last_prefix = prefix[0] = 0;
  13. for (size_t i=1; i<sample.length(); i++) {
  14. while (last_prefix > 0 && sample[last_prefix] != sample[i])
  15. last_prefix = prefix[last_prefix-1];
  16.  
  17. if (sample[last_prefix] == sample[i])
  18. last_prefix++;
  19.  
  20. prefix[i] = last_prefix;
  21. }
  22.  
  23. last_prefix = 0;
  24. for (size_t i=0; i<text.length(); i++) {
  25. while (last_prefix > 0 && sample[last_prefix] != text[i])
  26. last_prefix = prefix[last_prefix-1];
  27.  
  28. if (sample[last_prefix] == text[i])
  29. last_prefix++;
  30.  
  31. if (last_prefix == sample.length()) {
  32. cout << i + 1 - sample.length() << endl;
  33. }
  34. }
  35. }
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
0
3
8
11