题目链接
题目描述
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
示例
示例1:
输入:haystack = “hello”, needle = “ll” 输出:2
提示
0 <= haystack.length, needle.length <= 5 * 10-
思路
KMP算法
class Solution {private:void getNext(int* next, const string& t) {int j = 0;next[0] = 0;for (int i = 1; i < (int)t.size(); ++i) {while (j > 0 && t[i] != t[j]) {j = next[j - 1];}if (t[i] == t[j]) {++j;}next[i] = j;}}public:int strStr(string haystack, string needle) {if (needle.size() == 0) {return 0;}int* next = new int[needle.size()];getNext(next, needle);int j = 0;for (int i = 0; i < (int)haystack.size(); ++i) {while (j > 0 && haystack[i] != needle[j]) {j = next[j - 1];}if (haystack[i] == needle[j]) {++j;}if (j == needle.size()) {delete[] next;next = nullptr;return (i - needle.size() + 1);}}delete[] next;next = nullptr;return -1;}};
题解
复杂度分析
时间复杂度:
- 空间复杂度:
