strstr 在主串中查找子串首次出現位置。本文實現朴素匹配算法,分析邊界條件與常見錯誤。
#include <stdio.h>
#include <assert.h>
char *my_strstr(const char *haystack, const char *needle) {
assert(haystack && needle);
if (*needle == '\0') return (char *)haystack; // 空子串匹配開頭
const char *h = haystack;
while (*h) {
const char *h_start = h;
const char *n = needle;
while (*h && *n && *h == *n) {
h++;
n++;
}
if (*n == '\0') {
return (char *)h_start; // 找到,返回起點
}
h = h_start + 1; // 回溯到下一個起始位置
}
return NULL; // 未找到
}
int main() {
char *s1 = "abbbcdef";
char *s2 = "bbcd";
char *ret = my_strstr(s1, s2);
printf("結果:%s\n", ret ? ret : "NULL");
return 0;
}
s = p; 未聲明 s,且 q 未初始化h_start 作為潛在匹配起點h = h_start + 1 而非 h++(避免跳過字符)| 主串 | 子串 | 預期結果 | 說明 |
|---|---|---|---|
| "abbbcdef" | "bbcd" | "bbcdef" | 中間匹配 |
| "hello" | "world" | NULL | 不存在 |
| "aaaaa" | "aaa" | "aaaaa" | 重疊匹配,返回首個 |
| "abc" | "" | "abc" | 空子串 |
| "" | "a" | NULL | 空主串 |
朴素算法最壞 O(mn),KMP 通過預處理 next 數組達到 O(m+n)。面試常考,建議掌握。