#include "stdafx.h"
#include <string.h>
#include <iostream>
#include <vector>
using namespace std ;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
//模式匹配,kmp算法,复杂度O(m+n)
//返回匹配位置,-1表示匹配失败,传入匹配串和模式串和长度
//可更改元素类型,更换匹配函数
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
#define MAXN 100
#define _match(a,b) ((a)==(b))
typedef char elem_t;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
int kmp_match(int ls,elem_t* str,int lp,elem_t* pat)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)
...{
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
int fail[MAXN]=...{-1}, i=0,j;
for (j=1;j<lp;)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
...{
if(pat[i]!=pat[j] )
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
...{
fail[j++]=-1 ;
continue ;
}
for(i=0; j<lp && _match(pat[i],pat[j]) ; fail[j++]=i++) ;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
for (i=j=0;i<ls&&j<lp;i++)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
...{
if (_match(str[i],pat[j]))
j++;
else if (j)
j=fail[j-1]+1,i--;
}
return j==lp?(i-lp):-1;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
int kmp(string str1, string str2)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)
...{
if(str1.size()<str2.size())
return -1 ;
size_t i, j ;
vector<int> fail ;
fail.resize(str2.size(),-1) ;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
for(j=1, i=0; j<str2.size(); ++j)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
...{
if(str2[j]!=str2[i])
continue ;
for(i=0; j<str2.size() && str2[j]==str2[i] ; fail[j++]=i++) ;
--j ;
}
for (i=j=0; i<str2.size() && j<str1.size(); ++j)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
...{
if(str1[j]==str2[i])
++i ;
else if(i)
i=fail[i-1]+1, --j ;
}
return i==str2.size() ? j-i :-1 ;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
int _tmain(int argc, _TCHAR* argv[])
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)
...{
char * str1="abababababcabababa" ;
char * str2="ababababcab" ;
int i=kmp_match(strlen(str1),str1,strlen(str2),str2) ;
cout<<i<<endl ;
i=kmp(str1,str2) ;
cout<<i<<endl ;
getchar() ;
return 0;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
![](/skins/gray/images/speech.gif)
posted on
2007-07-14 19:32
sun_kang
阅读(
165)
评论()
编辑
收藏
举报