strstr 函數用于在主字符串中查找子字符串的首次出現位置,以下是高效的實現方案:
KMP算法優化版本
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 計算KMP算法的部分匹配表(PMT)
vector<int> getNext(const string& pattern) {
int m = pattern.length();
vector<int> next(m, 0);
for (int i = 1, j = 0; i < m; ) {
if (pattern[i] == pattern[j]) {
next[i++] = ++j;
} else if (j > 0) {
j = next[j - 1];
} else {
next[i++] = 0;
}
}
return next;
}
// KMP算法實現strstr
const char* myStrstr(const char* haystack, const char* needle) {
if (!ha