KMP字符串匹配算法

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 using namespace std;
 5 bool matched(string s,int k,int i)
 6 {
 7     bool result=true;
 8     int p=0;
 9     int q=i;
10     while(p<k)
11     {
12         if(s[p]==s[q])
13         {
14             p++;q--;
15         }
16         else
17         {
18             result=false;
19             break;
20         }
21     }
22     return result;
23 }
24 vector<int> find_next(string p)
25 {
26     vector<int> result;
27     result.push_back(0);
28     for(int i=1;i<p.length();i++)
29     {
30         int k=0;
31         for(k=i;k>0;k--)
32         {
33             if(matched(p,k,i))
34             {
35                 result.push_back(k);
36                 break;
37             }
38         }
39         if(k==0)
40             result.push_back(0);
41     }
42     return result;
43 }
44 int main()
45 {
46     string s,p;
47     cin>>s>>p;
48     
49     vector<int> next_index=find_next(p);
50     int index_s=0,index_p=0;
51     int matched=0;
52     while(index_s<s.length() && index_p<p.length())
53     {
54         if(s[index_s]==p[index_p])
55         {
56             index_s++;index_p++;matched++;
57         }
58         else if(matched==0)
59         {
60             index_s++;
61         }
62         else
63         {
64             index_p=matched-next_index[index_p-1];
65             matched=index_p-1;
66         }
67     }
68     if(index_p==p.length())
69     {
70         cout<<index_s-index_p<<endl;
71         system("pause");
72         return 0;
73     }
74     else
75     {
76         cout<<-1<<endl;
77         system("pause");
78         return 0;
79     }
80 }

posted on 2015-10-13 22:03  Riden  阅读(169)  评论(0编辑  收藏  举报

导航