代码改变世界

POJ 3461 Oulipo

2012-03-05 16:33  咆哮的马甲  阅读(163)  评论(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;
}