码迷,mamicode.com
首页 > 编程语言 > 详细

KMP字符串匹配算法

时间:2015-10-13 22:57:41      阅读:375      评论:0      收藏:0      [点我收藏+]

标签:

 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 }

KMP字符串匹配算法

标签:

原文地址:http://www.cnblogs.com/riden/p/4876052.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!