fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. vector<int> table(const string &w){
  5. int n = w.size();
  6. vector<int> t(n+1,-1);
  7. int c = 0;
  8. int p = 1;
  9. while(p<n){
  10. if(w[p]==w[c]) t[p] = t[c];
  11. else{
  12. t[p] = c;
  13. c = t[c];
  14. while(c>=0&&w[p]!=w[c])
  15. c = t[c];
  16. }
  17. p++; c++;
  18. }
  19. t[p] = c;
  20. return t;
  21. }
  22. vector<int> match(const string &s, const string &w){
  23. vector<int> t = table(w);
  24. cout<<"Table values of the word:"<<endl;
  25. for(int i=0; i<w.size(); i++) cout<<w[i]<<'\t';
  26. cout<<endl;
  27. for(int i=0; i<t.size(); i++) cout<<t[i]<<'\t';
  28. cout<<endl<<endl;
  29. int n = s.size();
  30. int j = 0;
  31. int k = 0;
  32. vector<int> p;
  33. while(j<n){
  34. if(w[k]==s[j]){
  35. j++; k++;
  36. if(k==w.size()){
  37. p.push_back(j-k);
  38. k = t[k];
  39. }
  40. }
  41. else{
  42. k = t[k];
  43. if(k<0){
  44. j++; k++;
  45. }
  46. }
  47. }
  48. return p;
  49. }
  50. int main() {
  51. string s;
  52. string w;
  53. cin>>s>>w;
  54. vector<int> ans = match(s,w);
  55. cout<<"The given word is matched in the string at following positions:"<<endl;
  56. for(int x: ans) cout<<x<<' ';
  57. cout<<endl;
  58. cout<<s<<endl;
  59. int j=0;
  60. for(int i=0; i<s.size()&&j<ans.size(); i++){
  61. if(i==ans[j]&&++j) cout<<'^';
  62. else cout<<' ';
  63. }
  64. cout<<endl;
  65. return 0;
  66. }
Success #stdin #stdout 0s 4304KB
stdin
abcdabcdabcdab
abcdabcd
stdout
Table values of the word:
a	b	c	d	a	b	c	d	
-1	0	0	0	-1	0	0	0	4	

The given word is matched in the string at following positions:
0 4 
abcdabcdabcdab
^   ^