【刷题日记】字符串-找出字符串中第一个匹配项的下标-L28-Easy
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
代码
KMP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| class Solution { public: void calNext(int *next, string &pattern) { int j = -1; next[0] = -1; for (int i = 1; i < pattern.length(); i++) { while (j != -1 && pattern[i] != pattern[j + 1]) { j = next[j]; } if (pattern[i] == pattern[j + 1]) { j += 1; } next[i] = j; } }
int KMP(string &text, string &pattern) { int next[pattern.length()]; calNext(next, pattern); int j = -1; for (int i = 0; i < text.length(); i++) { while (j != -1 && text[i] != pattern[j + 1]) { j = next[j]; } if (text[i] == pattern[j + 1]) { j++; } if (j == pattern.length() - 1) { return i - j; } } return -1; }
int strStr(string haystack, string needle) { return KMP(haystack, needle); } };
|