Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. /// O(n+m)
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. #define maxn 100005
  5. int failure[maxn];
  6.  
  7. void buil_failure_function(string pattern, int m)
  8. {
  9. failure[0] = 0;
  10. failure[1] = 0;
  11.  
  12. for(int i = 2; i <= m; i++){
  13. // i is the length of the prefix we are dealing with
  14. // j is the index of the largest next partial match
  15. // (the largest suffix/prefix) of the string under index i - 1;
  16.  
  17. int j = failure[i - 1];
  18. while(true){
  19. // check if the last character of prefix of length i "expands" the current "candidate"
  20. if(pattern[j] == pattern[i - 1]){
  21. failure[i] = j + 1;
  22. break;
  23. }
  24. // if we can't "expand" even the empty string
  25. if(j == 0){
  26. failure[i] = 0;
  27. break;
  28. }
  29. // else go to the next best "candidate" partial match
  30. j = failure[j];
  31. }
  32. }
  33. }
  34.  
  35. bool kmp(string text, string pattern)
  36. {
  37. int n = text.size();
  38. int m = pattern.size();
  39. buil_failure_function(pattern, m);
  40. int i = 0; // the initial state of the automation is the empty string
  41. int j = 0; // the first character of the string
  42.  
  43. while(true){
  44. if(j == n)
  45. return false; // reached the end of the text
  46.  
  47. // character matched
  48. if(text[j] == pattern[i]){
  49. i++; // change the state of the automation
  50. j++; // get the next character from the text
  51. if(i == m) return true;
  52. }
  53. else{
  54. if(i == 0){
  55. // if we reached the empty string and failed to
  56. // "expand" even it; we go to the next
  57. // character from the text, the state of the
  58. // automation remains zero
  59. j++;
  60. }
  61. else{
  62. // we try to "expand" the next best(largest) match
  63. i = failure[i];
  64. }
  65. }
  66. }
  67. return false;
  68. }
  69.  
  70.  
  71. int main()
  72. {
  73. string text, pattern;
  74. cin >> text >> pattern;
  75. cout << kmp(text, pattern)<<endl;
  76. return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement