Brute-Force算法

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 int BF(const string& father, const string& son)   //返回首次匹配的字符串中的第一个匹配的字符的下标
 6 {
 7     int i = 0, j = 0; //i表示主串下标,j表示子串下标
 8     while (i < father.size() && j < son.size())
 9     {
10         if (father[i] == son[j])
11         {
12             //i与j偏移相同的长度
13             ++i;
14             ++j;
15         }
16         else
17         {
18             i = i - j + 1; //i回溯到上次比较的下一个字符的下标处,从而继续与子串重新比较
19             j = 0;  //j变回初始下标0
20         }
21 
22     }
23     if (j == son.size())
24         return i - j;
25     else 
26         return -1;
27 
28 }
29 
30 int main()
31 {
32     string father = "12774578";
33     string son = "74";
34     cout << BF(father, son);
35 
36     return 0;
37 }
原文地址:https://www.cnblogs.com/FengZeng666/p/9453726.html