樸素字符串匹配(Naive String Matching)是最直觀的模式匹配算法。其核心思想是:在主串的每一個位置嘗試與模式串逐字符比對,一旦發現不匹配即移至主串下一位置重新開始,直到模式串完全匹配或主串遍歷結束。
a 的每個起始位置 tarindex。b 的對應字符。tarindex 遞增,繼續下一輪嘗試。#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int index(char *a, char *b) {
int tarindex = 0;
while (a[tarindex] != '\0') {
int tarlen = tarindex;
int patlen;
for (patlen = 0; b[patlen] != '\0'; ++patlen) {
if (a[tarlen++] != b[patlen]) {
break;
}
}
if (b[patlen] == '\0') {
return tarindex; // 匹配成功
}
++tarindex;
}
return -1; // 匹配失敗
}
int main() {
char *a = new char[1000];
char *b = new char[1000];
gets(a);
gets(b);
cout << "第 " << index(a, b) << " 個位置" << endl;
delete[] a;
delete[] b;
return 0;
}
樸素匹配在大數據量下效率較低,實際應用中常采用 KMP、Boyer-Moore 或 Sunday 等算法,通過預處理模式串跳過不必要的比對,將時間複雜度降至 O(m+n)。