您的位置:首页 > 其它

KMP matching

2010-06-10 11:41 162 查看
#include <iostream>
#include <string>

using namespace std ;

struct KeyWord
{
string strkey ;
int *matcher ;
} ;

void KMP_prefix(KeyWord &kw) ;
bool KMP_matcher(string &s, KeyWord &t) ;

int main()
{
string s = "12ababc5677" ;
KeyWord t ;
t.strkey = "77" ;
if (KMP_matcher(s, t))
{
cout << "SUCCESS" << endl ;
}
return 0 ;
}

void KMP_prefix(KeyWord &key)
{
int len = key.strkey.size() ;
key.matcher = new int[len] ;
key.matcher[0] = 0 ;
int k = -1, q ;
for (q = 1; q < len; ++q)
{
while ((k >= 0) && (key.strkey[k+1] != key.strkey[q]))
{
k = key.matcher[k] - 1 ;
}
if (key.strkey[k+1] == key.strkey[q])
{
++k ;
}
key.matcher[q] = k+1 ;
}
}

bool KMP_matcher(string &s, KeyWord &t)
{
int n = s.size() ;
int m = t.strkey.size() ;
KMP_prefix(t) ;
int q = -1, i ;
for (i = 0; i < n; ++i)
{
while ((q >= 0) && (t.strkey[q+1] != s[i]))
{
q = t.matcher[q] - 1 ;
}
if (t.strkey[q+1] == s[i])
{
++q ;
}
if (q+1 == m)
{
return true ;
}
}
return false ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: