题目链接

题目描述

实现 strStr() 函数。
给你两个字符串 haystackneedle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1

示例

示例1:

输入:haystack = “hello”, needle = “ll” 输出:2

提示

  • 0 <= haystack.length, needle.length <= 5 * 10
  • haystackneedle 仅由小写英文字符组成

    思路

    KMP算法

    1. class Solution {
    2. private:
    3. void getNext(int* next, const string& t) {
    4. int j = 0;
    5. next[0] = 0;
    6. for (int i = 1; i < (int)t.size(); ++i) {
    7. while (j > 0 && t[i] != t[j]) {
    8. j = next[j - 1];
    9. }
    10. if (t[i] == t[j]) {
    11. ++j;
    12. }
    13. next[i] = j;
    14. }
    15. }
    16. public:
    17. int strStr(string haystack, string needle) {
    18. if (needle.size() == 0) {
    19. return 0;
    20. }
    21. int* next = new int[needle.size()];
    22. getNext(next, needle);
    23. int j = 0;
    24. for (int i = 0; i < (int)haystack.size(); ++i) {
    25. while (j > 0 && haystack[i] != needle[j]) {
    26. j = next[j - 1];
    27. }
    28. if (haystack[i] == needle[j]) {
    29. ++j;
    30. }
    31. if (j == needle.size()) {
    32. delete[] next;
    33. next = nullptr;
    34. return (i - needle.size() + 1);
    35. }
    36. }
    37. delete[] next;
    38. next = nullptr;
    39. return -1;
    40. }
    41. };

    题解

    复杂度分析

  • 时间复杂度:0028-实现strStr() - 图1

  • 空间复杂度:0028-实现strStr() - 图2