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

hihocoder KMP算法

时间:2017-04-01 13:41:16      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:class   实现   algorithm   ace   str   思路   nbsp   std   space   

思路:

KMP模板。

实现:

 1 #include <cstdio>  
 2 #include <cstring>  
 3 #include <algorithm>  
 4 #include <iostream>  
 5 #include <string>  
 6 using namespace std;  
 7 
 8 int f[10005];  
 9 
10 void getfill(string s)  
11 {  
12     memset(f, 0, sizeof(f));
13     for(int i = 1; i < s.size(); i++)  
14     {  
15         int j = f[i];  
16         while(j && s[i] != s[j])  
17             j = f[j];  
18         f[i+1] = (s[i] == s[j]) ? j+1 : 0;  
19     }  
20 }  
21 
22 int find(string a, string s)  
23 {  
24     int ans = 0;  
25     getfill(s);
26     int j = 0;  
27     for(int i = 0; i < a.size(); i++)  
28     {  
29         while(j && a[i] != s[j])  
30             j = f[j];  
31         if(a[i] == s[j])  
32             j ++;  
33         if(j == s.size())
34         {  
35             ans ++;  
36         }  
37     }  
38     return ans;  
39 } 
40 
41 int main()
42 {
43     int n;
44     cin >> n;
45     string a, b;
46     for(int i = 0; i < n; i++)
47     {
48         cin >> a >> b;
49         cout << find(b, a) << endl;
50     }
51     return 0;
52 }

 

hihocoder KMP算法

标签:class   实现   algorithm   ace   str   思路   nbsp   std   space   

原文地址:http://www.cnblogs.com/wangyiming/p/6655491.html

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