Brute Force:
1 class Solution { 2 public: 3 int strStr(char *haystack, char *needle) { 4 if (!haystack) return -1; 5 if (!needle) return 0; 6 int index = 0, tmp1 = 0, tmp2 = 0; 7 while (haystack[index]) { 8 if (haystack[index] == needle[0]) { 9 char *tmp1 = haystack, *tmp2 = needle; 10 while (tmp1 && tmp2 && *tmp1 == *tmp2) { 11 tmp1++; 12 tmp2++; 13 } 14 if (!tmp2) return index; 15 } 16 index++; 17 } 18 return -1; 19 } 20 };
KMP:
Intialize a dp map for search whether there has duplicate chars in needle.
j = dp[i-1] is starting from the previous step
1 class Solution { 2 public: 3 int strStr(char *haystack, char *needle) { 4 if (!haystack) return -1; 5 if (!needle) return 0; 6 int len = strlen(needle), i = 0, j = 0; 7 vector<int> dp(len, -1); 8 for (int i = 1; i < len; i++) { 9 for (j = dp[i-1]; j >= 0 && needle[i] != needle[j+1]; j = dp[j]); 10 if (needle[i] == needle[j+1]) dp[i] = j+1; 11 } 12 i = 0, j = 0; 13 while (haystack[i] && needle[j]) { 14 if (haystack[i] == needle[j]) { 15 i++; 16 j++; 17 } else if (j == 0) i++; 18 else j = dp[j-1] + 1; 19 } 20 if (needle[j]) return -1; 21 return i-j; 22 } 23 };
.
时间: 2024-11-06 17:40:51