主串 S 長度 n,模式串 T 長度 m。逐位比對,失敗時主串回溯到下一起始位置,模式串回到開頭。
bool search_str(char *s, char *t) {
int i = 0, j = 0;
while (s[i] && t[j]) {
if (s[i] == t[j]) { i++; j++; }
else { i = i - j + 1; j = 0; }
}
return t[j] == '\0'; // 完整匹配
}
提供的程式碼包含:
searchstr:遞迴/迭代查找主體cmpstr:子字串比對輔助函數chazhao:封裝介面,印出發現位置使用 iostream.h 舊式標頭、void main() 非標準寫法,建議現代化:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool find_substr(const char *haystack, const char *needle) {
size_t n = strlen(haystack), m = strlen(needle);
for (size_t i = 0; i <= n - m; i++)
if (strncmp(haystack + i, needle, m) == 0)
return true;
return false;
}
| 演算法 | 時間複雜度 | 特點 |
|---|---|---|
| KMP | O(n+m) | 預處理 next 陣列避免回溯 |
| Boyer-Moore | O(n/m) 最佳 | 從右向左比對、壞字符/好後綴規則 |
| Sunday | O(n) 平均 | BM 改良、看主串下一字符決定跳躍 |
| Rabin-Karp | O(n+m) 平均 | 滾動雜湊、適合多模式匹配 |
教學階段掌握暴力法邏輯,工程專案建議使用標準庫 strstr 或成熟演算法實作。