Implement strStr()
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
方法:KMP
正好趁这个题目温习了一下KMP字符串匹配。母串S, 模式串P
KMP算法是利用模式串P本身的特性来降低复杂度。通过next函数or覆盖函数来优化。
本质上,next函数/覆盖函数是overlap[i]是求出P[0~i]内的最大的前缀P[0~i-x]和后缀P[x~i]的长度。
#include <cstring> #include <iostream> using namespace std; class Solution { public: char *strStr(char *haystack, char *needle) { int lenh = strlen(haystack); int lenn = strlen(needle); if (lenn == 0) return haystack; int idx = kmp_search(haystack, needle, lenh, lenn); if (idx == -1) return NULL; else return haystack + idx; } int kmp_search(char* t, char* p, int lt, int lp) { int *over = new int[lp]; calc_overlap(over, p); int k = -1; for (int i = 0; i < lt; ++i) { while (k >= 0 && p[k+1] != t[i]) k = over[k]; if (p[k+1] == t[i]) k++; if (k == lp - 1) return i - k; } return -1; } void calc_overlap(int *over, char *str) { over[0] = -1; int k = -1; for (int i = 1; i < strlen(str); ++i) { while (k >= 0 && str[k+1] != str[i]) k = over[k]; if (str[k+1] == str[i]) k++; over[i] = k; } } };
N^2
class Solution { public: char *strStr(char *haystack, char *needle) { int l1 = strlen(haystack); int l2 = strlen(needle); if (l2 == 0) return haystack; char *s = haystack; while (*s != '\0') { if (l1 < l2) return NULL; if (cmp(s, needle)) return s; s++; l1--; } return NULL; } bool cmp(char* hay, char* ne) { while (*hay != '\0' && *ne != '\0') { if (*hay == *ne) { hay++, ne++; continue; } else return false; } if (*ne == '\0') return true; else return false; } };