目 录CONTENT

文章目录
C

朴素字符串匹配

~梓
2025-09-18 / 0 评论 / 0 点赞 / 3 阅读 / 0 字
温馨提示:
部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
#include <stdio.h>
#include <string.h>

// 朴素字符串匹配算法
int naiveMatch(char* text, char* pattern) {
    int n = strlen(text);
    int m = strlen(pattern);

    for (int i = 0; i <= n - m; i++) {
        int j;
        for (j = 0; j < m; j++) {
            if (text[i + j] != pattern[j]) {
                break;
            }
        }
        if (j == m) {
            return i;  // 返回匹配的起始位置
        }
    }
    return -1;  // 没有找到匹配
}

int main() {
    char text[] = "ABACADABRAC";
    char pattern[] = "ABRA";

    int pos = naiveMatch(text, pattern);

    if (pos != -1) {
        printf("找到匹配,起始位置: %d\n", pos);
    }
    else {
        printf("未找到匹配\n");
    }

    return 0;
}
  • 时间复杂度:最坏 O(n×m)
  • 空间复杂度:O(1)
0

评论区