C++ kmp算法模板代碼解讀
作者:佚名 
  我們在這篇文章中主要為大家詳細介紹了C++ kmp算法模板的相關(guān)應(yīng)用方法,希望大家可以從這段代碼中學(xué)到更多的應(yīng)用技巧。
 C++編程語言中的模板應(yīng)用是一個比較復(fù)雜的應(yīng)用技術(shù),我們今天就先從C++ kmp算法模板的基本應(yīng)用開始學(xué)習(xí),從而加深我們對這方面知識的認識程度,方便將來的應(yīng)用,提高編程效率。
在使用的時候加上這兩行代碼就行了
- #include < vector>
 - using namespace std;
 
C++ kmp算法模板參數(shù)說明 #t#
const T *source 待匹配的字符串
TL sourceLen 待匹配字符串的長度
const T *pattern 模式串
TL 模式串長度
C++ kmp算法模板代碼示例:
- template < class T,class TL>
 - inline int kmpmatch(const T *source,TL sourceLen,
 
const T *pattern,TL patternLen)- {
 - vector< int> next;
 - for ( int i = 0; i < patternLen ; i ++ )
 - next.push_back(0);
 - next[0] = -1;
 - for( int i = 1 ; i < patternLen ; i ++ )
 - {
 - int j = next[i - 1];
 - while ( (pattern[i] != pattern[i + 1])&& (j >= 0))
 - {
 - j = next[j];
 - }
 - if ( pattern[i] == pattern[j + 1])
 - {
 - next[i] = j + 1;
 - }
 - else
 - {
 - next[i] = -1;
 - }
 - }
 - int i = 0;
 - int j = 0;
 - while (( i < sourceLen ) && ( j < patternLen ))
 - {
 - if ( source[i] == pattern[j] )
 - {
 - i ++;
 - j ++;
 - }
 - else if ( j == 0 )
 - {
 - i ++;
 - }
 - else
 - {
 - j = next[j - 1 ] + 1;
 - }
 - }
 - if ( j >= patternLen )
 - {
 - if ( !next.empty() )
 - next.clear();
 - return i - patternLen ;
 - }
 - else
 - {
 - if ( !next.empty() )
 - next.clear();
 - return -1;
 - }
 - }
 
以上就是對C++ kmp算法模板的相關(guān)介紹。
責(zé)任編輯:曹凱 
                    來源:
                    博客園
 














 
 
 



 
 
 
 