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 &pattern, vector<int> &prefix) {
prefix[0] = -1;
size_t i_offset = 1, p_offset = 0;
while (i_offset < prefix.size() - 1) {
if (p_offset != -1 && pattern[p_offset] != pattern[i_offset])
p_offset = prefix[p_offset];
else
prefix[++i_offset] = ++p_offset;
}
}
int KMP_match(const string &text, const string &pattern, const vector<int> &prefix) {
int match_time = 0;
size_t t_offset = 0, p_offset = 0;
while (t_offset < text.size()) {
if (p_offset == -1 || 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 i = 0; i < test_count; i++) {
string pattern, text;
cin >> pattern >> text;
vector<int> prefix(pattern.size() + 1, 0);
compute_prefix(pattern, prefix);
cout << KMP_match(text, pattern, prefix) << endl;
}
return