首页 > 其他 > 详细

hihoCoder #1015 KMP

时间:2015-03-26 12:15:20      阅读:158      评论:0      收藏:0      [点我收藏+]

 

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 
 5 using namespace std;
 6 
 7 void compute_prefix(const string &pattern, vector<int> &prefix) {
 8     prefix[0] = -1;
 9     size_t i_offset = 1, p_offset = 0;
10     while (i_offset < prefix.size() - 1) {
11         if (p_offset != -1 && pattern[p_offset] != pattern[i_offset])
12             p_offset = prefix[p_offset];
13         else
14             prefix[++i_offset] = ++p_offset;
15     }
16 }
17 int KMP_match(const string &text, const string &pattern, const vector<int> &prefix) {
18     int match_time = 0;
19     size_t t_offset = 0, p_offset = 0;
20     while (t_offset < text.size()) {
21         if (p_offset == -1 || text[t_offset] == pattern[p_offset]) {
22             t_offset++; p_offset++;
23             if (p_offset == pattern.size()) match_time++;
24         }
25         else 
26             p_offset = prefix[p_offset];
27     }
28     return match_time;
29 }
30 int main() {
31     int test_count;
32     cin >> test_count;
33     for (int i = 0; i < test_count; i++) {
34         string pattern, text;
35         cin >> pattern >> text;
36         vector<int> prefix(pattern.size() + 1, 0);
37         compute_prefix(pattern, prefix);
38         cout << KMP_match(text, pattern, prefix) << endl;
39     }
40     return 0;
41 }

 

#include <iostream>
#include <string>
#include <vector>
 
using namespace std;
 
void compute_prefix(const string &patternvector<int&prefix{
	prefix[0-1;
	size_t i_offset 1p_offset 0;
	while (i_offset prefix.size() 1{
		if (p_offset != -&& pattern[p_offset!= pattern[i_offset])
			p_offset prefix[p_offset];
		else
			prefix[++i_offset++p_offset;
	}
}
int KMP_match(const string &textconst string &patternconst vector<int&prefix{
	int match_time 0;
	size_t t_offset 0p_offset 0;
	while (t_offset text.size()) {
		if (p_offset == -|| text[t_offset== pattern[p_offset]) {
			t_offset++; p_offset++;
			if (p_offset == pattern.size()) match_time++;
		}
		else 
			p_offset prefix[p_offset];
	}
	return match_time;
}
int main() {
	int test_count;
	cin >> test_count;
	for (int 0test_counti++) {
		string patterntext;
		cin >> pattern >> text;
		vector<intprefix(pattern.size() 10);
		compute_prefix(patternprefix);
		cout << KMP_match(textpatternprefix<< endl;
	}
	return 0;
}

hihoCoder #1015 KMP

原文:http://www.cnblogs.com/sworder/p/4368111.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!