234234234

朴素模式匹配算法-串

朴素的意思就是简单的算法(常规思路)。

 

朴素模式匹配的升级版算法是KMP算法(通过next数组大幅度加快匹配,使主串下标i不再回溯)。

推荐博客(思路):https://blog.csdn.net/yutong5818/article/details/81319120

 

// 朴素匹配算法代码

// 最坏时间复杂度O(nm) n,m分别表示主串与模式串的长度,每一次匹配到模式串的最后一个字符才匹配失败。

// 最好的时间复杂度O(n),在模式串匹配第一个字符就匹配失败。

#include <stdio.h>

int naiveAlgo(const char * MStr, int MStrL, const char *PStr, int PStrL) {
    int i = 1,j = 1;
    while(i <= MStrL && j <= PStrL) {
        // 操作的下表从1开始,取值的下表是从0开始 
        if (MStr[i-1] == PStr[j-1]) {
            i++;
            j++; 
        } else {
            // 当匹配失败时,为下一次匹配做准备 
            i = i - j + 2; 
            j = 1;
        }
    }
    
    // 匹配成功时,j = PStrl + 1 
    if (j > PStrL) {
        // 匹配成功,返回模式串第一个在主串中的位标 
        return i - PStrL;
    } else {
        // 匹配失败时,返回0 
        return 0;
    }
}

int main() {

    const char * mstr = "123456"; // 主串 
    const char * pstr = "456"; // 模式串 
    int index = naiveAlgo(mstr, 6, pstr, 3);
    printf("%d\n", index);
    return 0; 
} 

 

 

。。。

posted @ 2022-04-09 18:46  你若愿意,我一定去  阅读(273)  评论(0编辑  收藏  举报
23423423423