POJ 3461 Oulipo
2012-03-05 16:33 咆哮的马甲 阅读(164) 评论(0) 编辑 收藏 举报利用KMP算法查找字符串中字串出现的次数
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int* computeOverlap(string& s)
{
int length = s.length();
if(length == 0)
return NULL;
int* overlayValue = new int[length];
overlayValue[0] = -1;
for(int i=1; i<length; i++)
{
int index = overlayValue[i-1];
while(index>=0 && s[index+1] != s[i])
{
index = overlayValue[index];
}
if(s[index+1] == s[i])
{
overlayValue[i] = index+1;
}
else
{
overlayValue[i] = -1;
}
}
return overlayValue;
}
int KMP_Match(string& w, string& t)
{
int matchCount = 0;
int* overlayValue = computeOverlap(w);
int wLen = w.length();
int tLen = t.length();
int wIndex = 0;
int tIndex = 0;
while(wIndex < wLen && tIndex < tLen)
{
if(w[wIndex] == t[tIndex])
{
if(wIndex == wLen-1)
{
matchCount++;
if(wIndex == 0)
wIndex = -1;
else
wIndex = overlayValue[wIndex];
}
wIndex++;
tIndex++;
}
else if(wIndex == 0)
{
tIndex++;
}
else
{
wIndex = overlayValue[wIndex-1]+1;
}
}
delete[] overlayValue;
return matchCount;
}
int main()
{
int count = 0;
cin>>count;
vector<string> W;
vector<string> T;
W.resize(count);
T.resize(count);
for(int i=0; i<count; i++)
{
cin>>W[i];
cin>>T[i];
}
for(int i=0; i<count; i++)
{
cout<<KMP_Match(W[i],T[i])<<endl;
}
return 0;
}
作者:咆哮的马甲
出处:http://www.cnblogs.com/arthurliu/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
转载请保持文档的完整性,严禁用于任何商业用途,否则保留追究法律责任的权利。