Question:
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
Solution (C++):
class Solution {
public:
char *strStr(char *haystack, char *needle) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int len_needle = strlen(needle);
int len_haystack = strlen(haystack);
if(len_needle == 0) return haystack;
if(len_needle > len_haystack) return NULL;
char *s1;
char *s2 = needle;
char *cp = haystack;
char *s1Adv = haystack;
while(*++s2) {
s1Adv++;
}
while(*s1Adv)
{
s1 = cp;
s2 = needle;
while(*s1 && *s2 && *s1 == *s2)
{
s1++;
s2++;
}
if(!*s2) return cp;
cp++;
s1Adv++;
}
return NULL;
}
};
以上是比较straight-forward的实现方式,也可以用经典高效的KMP算法实现:
class Solution {
public:
void compute_prefix(char* T, int m, vector<int>& pi) {
int i = 0;
int j = pi[0] = -1;
while (i < m) {
while (j > -1 && T[i] != T[j]) {
j = pi[j];
}
++i;
++j;
pi[i] = (T[i] == T[j]) ? (pi[j]) : (j);
}
}
char *strStr(char *haystack, char *needle) {
int n = strlen(haystack);
int m = strlen(needle);
if (m == 0) {
return haystack;
}
vector<int> pi(m+1);
compute_prefix(needle, m, pi);
int i = 0;
int j = 0;
while (i < n) {
while (j > -1 && haystack[i] != needle[j]) {
j = pi[j];
}
++i;
++j;
if (j >= m) {
return haystack+i-j;
}
}
return 0;
}
};