Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.72 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> array_temporario(string & padrao){
  5.     vector<int> index; int j, i;
  6.     for(i = 0; i < padrao.length();)
  7.         if(padrao[i] == padrao[j]){
  8.             index[i] = j + 1; j++; i++;
  9.         } else {
  10.             index[i] = 0; i++;
  11.         }
  12.     return index;
  13. }
  14.  
  15. bool KMP(string & texto, string & padrao){
  16.     vector<int> index = array_temporario(padrao);
  17.     int i = 0, j = 0;
  18.     while(i < texto.length() && j < padrao.length()){
  19.         if(texto[i] == padrao[j]){
  20.             i++; j++;
  21.         } else {
  22.             if(j != 0) j = index[j-1];
  23.             else i++;
  24.         }
  25.     }
  26.     if(j == padrao.length()) return true;
  27.     return false;
  28. }
  29.  
  30. int main(){
  31.     string texto = "abcxabcdabcdabcy", padrao = "abcdabcy";
  32.     cout << KMP(texto, padrao) << endl;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement