Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
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().
题意
实现找子串函数
题解
1 class Solution { 2 public: 3 int* findNext(string P) { 4 int i, k; 5 int m = P.length(); 6 int *next = new int[m]; 7 next[0] = -1; 8 i = 0; k = -1; 9 while (i < m - 1) { 10 while (k >= 0 && P[k] != P[i]) 11 k = next[k]; 12 i++, k++; 13 if (P[k] == P[i]) 14 next[i] = next[k]; 15 else next[i] = k; 16 } 17 return next; 18 } 19 int strStr(string haystack, string needle) { 20 if (needle == "")return 0; 21 int *next = findNext(needle); 22 int p1 = 0, p2 = 0; 23 int l1 = haystack.length(), l2 = needle.length(); 24 while (p1 < l1&&p2 < l2) { 25 if (haystack[p1] == needle[p2]) { 26 p1++, p2++; 27 continue; 28 } 29 p2 = next[p2]; 30 if (p2 == -1) { 31 p1++; p2 = 0; 32 } 33 } 34 if (p2 != l2)return -1; 35 return p1 - l2; 36 } 37 };
说到找子串就是kmp啦