您的位置:首页 > 其它

[HihoCoder]#1015 : KMP算法

2016-06-23 20:54 477 查看
华电北风吹

天津大学认知计算与应用重点实验室

2016-06-23

题目链接:http://hihocoder.com/problemset/problem/1015

题目分析:KMP模板代码。

// problem1014.cpp : 定义控制台应用程序的入口点。
// KMP算法
// http://hihocoder.com/problemset/problem/1015 // 张正义 2016-04-12

#include "stdafx.h"

#include <iostream>
#include <vector>
#include <string>
using namespace std;

vector<int> nextVector(string pattern)
{
int m = pattern.size();
vector<int> result(m);
for (int i = 1; i < m; i++)
{
int j = result[i - 1];
while (j&&pattern[i] != pattern[j])
j = result[j - 1];
result[i] = pattern[i] == pattern[j] ? j + 1 : 0;
}
return result;
}

int KMP(string str, string pattern)
{
int n = str.size(), m = pattern.size();
vector<int> arr = nextVector(pattern);
int count = 0;
int p = 0;
for (int i = 0; i < n; i++)
{
while (p>0 && pattern[p] != str[i])
p = arr[p - 1];
if (str[i] == pattern[p])
p++;
if (p == m)
count++;
}
return count;
}

int main(int argc, char* argv[])
{
int n;
cin >> n;
string pattern, line;
for (int i = 0; i < n; i++)
{
cin >> pattern;
cin >> line;
cout << KMP(line, pattern) << endl;
}
return 0;
}


结题报告:经典代码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: