28. 实现 strStr()
题目
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
解答
本题考察的是字符串模式匹配,可以视为KMP算法的模版题,当然也可以使用BM算法。在此讲解KMP算法,巩固自身印象。
KMP算法
本题解答
void buildnext(char* needle, int* next) {
int length = strlen(needle);
int i = 0;
next[0] = -1;
for (i; i < length-1; i++) {//已知next[i],即i-1最长前后缀,求next[i+1],即i最长前后缀
int k = next[i];
while (k != -1 && needle[k] != needle[i]) {
k = next[k];
}
next[i + 1] = k+1;
}
}
int strStr(char* haystack, char* needle) {
int next[10020];
buildnext(needle, next);
int i = 0;
int j = 0;
int length1 = strlen(haystack);
int length2 = strlen(needle);
while (i<length1 && j<length2) {
if (j == -1 || haystack[i] == needle[j]) {
i++;
j++;
}
else {
j = next[j];
}
}
if (j == strlen(needle)) return i - j;
else return -1;
}
自身犯的错误
最开始能通过oj的一部分检测出点,通不过另一部分。按理来说逻辑顺畅的话KMP算法能很顺溜的一遍过。于是拿错误样例在本地调试。发现了问题。
strlen 是unsigned类型,不能直接与-1作比较,否则得到的结果布尔值不正确。解决办法是int length=strlen或者直接强制类型转化成int 型。