28. 实现strStr()
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
1 2
| 输入: haystack = "hello", needle = "ll" 输出: 2
|
示例 2:
1 2
| 输入: haystack = "aaaaa", needle = "bba" 输出: -1
|
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
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
| class Solution { public: void getNext(string ps, int* next) { next[0] = -1; int j = 0; int k = -1; while(j < ps.length() - 1) { if(k == -1 || ps[j] == ps[k]) { next[++j] = ++k; } else { k = next[k]; } } }
void getNext2(string ps, int* next) { next[0] = -1; int j = 0; int k = -1; while(j < ps.length() - 1) { if(k == -1 || ps[j] == ps[k]) { if(ps[++j] == ps[++k]) { next[j] = next[k]; } else { next[j] = k; } } else { k = next[k]; } } }
int KmpSearch(string s, string p) { int i = 0; int j = 0; int sLen = s.length(); int pLen = p.length(); int next[p.length()] = {0}; getNext2(p, next); while(i < sLen && j < pLen) { if(j == -1 || s[i] == p[j]) { i++; j++; } else { j = next[j]; } } if(j == pLen) { return i - j; } else { return -1; } }
int strStr(string haystack, string needle) { if(needle.length() == 0) { return 0; } return KmpSearch(haystack, needle); } };
|
解释:就是很麻烦…用到了KMP算法
