当前位置:   article > 正文

leetcode_30 Implement strStr()

leetcode_30 Implement strStr()

题目:

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

  1. Input: haystack = "hello", needle = "ll"
  2. Output: 2

Example 2:

  1. Input: haystack = "aaaaa", needle = "bba"
  2. Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

采用KMP算法:详见文章strstr的实现--KMP

  1. class Solution {
  2. public:
  3. vector<int> getnext(string needle)
  4. {
  5. int n = needle.length();
  6. vector<int> lps(n,0);
  7. for(int i = 1,len = 0 ; i < n ;)
  8. {
  9. if(needle[i] == needle[len])
  10. lps[i++] = ++len;
  11. else if(len)
  12. {
  13. len = lps[len - 1];
  14. }else
  15. {
  16. lps[i++] = 0;
  17. }
  18. }
  19. return lps;
  20. }
  21. int strStr(string haystack, string needle) {
  22. int n = needle.length();
  23. if(n == 0)
  24. {
  25. return 0;
  26. }
  27. int h = haystack.length();
  28. if(h == 0)
  29. {
  30. return -1;
  31. }
  32. vector<int> next = getnext(needle);
  33. int i, j;
  34. for(i = 0,j = 0; i < h ;)
  35. {
  36. if(haystack[i] == needle[j])
  37. {
  38. i++;
  39. j++;
  40. }
  41. if(j == n)
  42. return i - j;
  43. if(i < h && haystack[i] != needle[j])
  44. {
  45. if(j > 0)
  46. {
  47. j = next[j -1];
  48. }
  49. else{
  50. i++;
  51. }
  52. }
  53. }
  54. return -1;
  55. }
  56. };

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/658674
推荐阅读
相关标签
  

闽ICP备14008679号