Advertisement
Guest User

Untitled

a guest
Jan 16th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. vector<int> KMP(string S, string K)
  7. {
  8. vector<int> T(K.size() + 1, -1);
  9. vector<int> matches;
  10.  
  11. if(K.size() == 0)
  12. {
  13. matches.push_back(0);
  14. return matches;
  15. }
  16. for(int i = 1; i <= K.size(); i++)
  17. {
  18. int pos = T[i - 1];
  19. while(pos != -1 && K[pos] != K[i - 1]) pos = T[pos];
  20. T[i] = pos + 1;
  21. }
  22.  
  23. int sp = 0;
  24. int kp = 0;
  25. while(sp < S.size())
  26. {
  27. while(kp != -1 && (kp == K.size() || K[kp] != S[sp])) kp = T[kp];
  28. kp++;
  29. sp++;
  30. if(kp == K.size()) matches.push_back(sp - K.size());
  31. }
  32.  
  33. return matches;
  34. }
  35.  
  36. int main()
  37. {
  38. string A,B;
  39. cout << "Input the text&pattern in the following order: text first, pattern second:";
  40.  
  41. cin >> A;
  42. cin >> B;
  43.  
  44. vector<int> returnValue = KMP(A, B); // do KMP match and store the result in returnValue
  45.  
  46. for (int i = 0; i < returnValue.size(); i ++)
  47. {
  48. cout << returnValue[i] << endl;
  49. }
  50.  
  51. return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement