字符串的模式匹配

    字符串的模式匹配问题描述如下:若打算在字符串T中查找是否包含子串与字符串P相等,则称字符串T为目标,P为模式,并称这个查找的过程为串的模式匹配。

    BF模式匹配:这个模式匹配算法是由Brute和Foece提出的。其基本思想为:

   (1)初始时让两字符串的起始位置对齐。

   (2)顺序比较两个字符串,比较结果有如下三种可能:

            1.匹配成功,则将目标串的比较指针的指向位置减去模式串的长度返回,即为匹配成功的位置。

            2.匹配过程中匹配失败,则目标串的比较指针指向上次比较的起始位置的下一位,模式串指向模式串的起点。

            3.匹配时发现目标串的剩余字符长度小于模式串的长度,则匹配失败。

    假设目标串T为"aaaacxhdsse",模式串P为"aac",这串的模式匹配过程如下:

                                                                0        1        2        3        4        5        6        7        8        9        10        11


 第一趟                                                     a        a        a        a        c        x         h        d        s        s         e

                                                                 a         a       c!


 第二趟                                                     a        a        a        a        c        x         h        d        s        s         e

                                                                           a         a       c!


 第三趟                                                      a        a        a        a       c        x         h        d        s        s         e

                                                                                      a         a       c


      由图可知,第三趟匹配结束之后,字符串的模式匹配完成!!!

BF模式匹配代码如下:

#include <iostream>
#include <string>
using namespace std;

int Index(string s, string t){
    int lens = s.length();//计算串s、t的长度
    int lent = t.length();
    int i = 0;
    int j = 0;
    while (i < lens&&j < lent){//如果i、j都各自小于lens和lent
        if (t[j] == s[i]){//如果子串的t[j]和主串的s[i]相等
            ++i;//各自索引都自增
            ++j;
        }
        else{//否则,主串的索引比刚开始后移一个;子串的索引变为0
            i = i - j + 1;
            j = 0;
        }
    }
    if (j == lent){//如果最j和lent的大小一样,证明找到了,返回子串在主串中的索引
        return i - lent + 1;
    }
    else{//否则返回-1
        return -1;
    }
}

int main(){
    string s,t;
    cin>>s;
    cin>>t;
    int pos = Index(s, t);
    if (pos != -1){
        cout << "find " << t << " at the index " << pos << " of " << s << endl;
    }
    else{
        cout << "can't find " << t << " in " << s << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Wangguang_/article/details/81096926