Advertisement
Guest User

Untitled

a guest
Sep 24th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. class Solution {
  2. public:
  3. int strStr(string haystack, string needle) {
  4. int lenH = haystack.size(), lenN = needle.size();
  5. if(lenH < lenN)return -1;
  6.  
  7. //KMP, calculate next array
  8. vector<int> next(lenN + 1, -1);
  9. int k = -1, i = 0;
  10. while(i < lenN)
  11. {
  12. if(k == -1 || needle[i] == needle[k])
  13. next[++i] = ++k;
  14. else
  15. k = next[k];
  16. }
  17.  
  18. int j = 0;
  19. i = 0;
  20. while(i < lenH && j < lenN)
  21. {
  22. if(j == -1 || haystack[i] == needle[j])
  23. {
  24. ++i;
  25. ++j;
  26. }
  27. else
  28. j = next[j];
  29. }
  30.  
  31. return j == lenN? i - lenN: -1;
  32. }
  33. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement