朴素的模式匹配算法BF

 

 

 

 

 1 #include <iostream>
 2 using namespace std;
 3 int BF(char S[], char T[]);
 4 int main()
 5 {
 6     char s1[100], s2[10];
 7     int index = 0;
 8     cout << "请输入主串:" << endl;
 9     cin >> s1;
10     cout << "请输入模式串:" << endl;
11     cin >> s2;
12     index = BF(s1, s2);
13     if (index==0)
14     {
15         cout << s2 << "不是" << s1 << "的子串" << endl;
16 
17     } 
18     else
19     {
20         cout << s2 << "" << s1 << "的位置是"<<index << endl;
21     }
22     return 0;
23 }
24 int BF(char S[], char T[])
25 {
26     int start = 0;//主串从下标0开始第一趟匹配
27     int i= 0,j=0;/*设置比较的起始下标*/
28     while ((S[i]!='\0')&&(T[j]!='\0'))
29     {
30         if (S[i]==T[j])
31         {
32             ++i; ++j;
33         }
34         else
35         {
36             i = i - j + 1, j = 0;//start++; i = start; j = 0;/*i和j分别回溯*/
37         }
38     }
39     if (T[j]=='\0')
40     {
41         return i - j + 1;//start + 1;//返回本趟匹配的起始位置(不是下标)
42     }
43     else
44     {
45         return 0;
46     }
47 }

 

posted @ 2020-11-23 10:50  丁帅帅dss  阅读(157)  评论(0)    收藏  举报