Fork me on GitHub

算法之美--3.2.2 MP算法

这块硬骨头,放在这里半年的时间了,一直没有动,今天周末看看,书上把过程写的比较详细,自己基本也看懂了,但是对代码本身的编写还是比较生疏,要经常复习,估计才能看透,后面有看了kmp;这两者之间的关系也是头大。。。

 1 /*!
 2  * \file MP_算法.cpp
 3  *
 4  * \author ranjiewen
 5  * \date 2017/02/12 15:06
 6  *
 7  * 
 8  */
 9 
10 void preMp(const char *pattern, int m, int mpNext[]) //m为pattern的长度
11 {
12     int i, j;
13     i = 0;
14     j = mpNext[0] = -1;
15     while (i<m)
16     {
17         while (j>-1&&pattern[i]!=pattern[j]) //
18         {
19             j = mpNext[j];
20         }
21         mpNext[++i] = ++j;  //mpNext(j)=f(j-1)+1
22     }
23 }
24 
25 #include <iostream>
26 #include <string>
27 using namespace std;
28 
29 void MP(string pattern, string target)
30 {
31     int m = pattern.length();
32     int n = target.length();
33     if (m>n)
34     {
35         cerr << "Unsuccessful match!" << endl;
36         return;
37     }
38     const char* x = pattern.c_str();
39     const char* y = target.c_str();
40     int i = 0, j = 0, mpNext[128];  //m+1大小
41 
42     preMp(x, m, mpNext);  //mpNext 进行一下轮比较过程中模式P的起始比较位置
43 
44     bool flag = false;
45     while (i<n)   //i 遍历target字符串
46     {
47         while (j>-1&&x[j]!=y[i])  //j 匹配模式字符串
48         {
49             j = mpNext[j];
50         }
51         j++;
52         i++;
53 
54         if (j>=m)
55         {
56             cout << "Matching index found at:" << i - j << endl;
57             j = mpNext[j];  //匹配后面的子串
58             flag = true;
59         }
60     }
61     if (!flag)
62     {
63         cout << "Unsuccessful match=-====!";
64     }
65 }
66 
67 int main(int argc, char** argv)
68 {
69     string p1 = "abcabcad";
70     string p2 = "adcadcad";
71     string p3 = "ababcaabc";
72     string t = "ctcabcabcadtcaabcabcaaatabcabcad";
73 
74     cout << "MP_p1 : " << endl;
75     MP(p1, t);
76     cout << endl;
77 
78     cout << "MP_p2 : " << endl;
79     MP(p2, t);
80     cout << endl;
81 
82     cout << "MP_p3 : " << endl;
83     MP(p3, t);
84     cout << endl;
85 
86     string t1 = "ctcaatcacaatcat";
87     string p4 = "caatcat";
88     MP(p4, t1);
89     cout << endl;
90     return 0;
91 }

 

posted @ 2017-02-12 20:12  ranjiewen  阅读(1223)  评论(0编辑  收藏  举报