C++ kmp算法模板代码解读

C++编程语言中的模板应用是一个比较复杂的应用技术,我们今天就先从C++ kmp算法模板的基本应用开始学习,从而加深我们对这方面知识的认识程度,方便将来的应用,提高编程效率。

在使用的时候加上这两行代码就行了

 
 
 
  1. #include < vector>   
  2. using namespace std; 

 

C++ kmp算法模板参数说明 #t#

const T *source 待匹配的字符串

TL sourceLen 待匹配字符串的长度

const T *pattern 模式串

TL 模式串长度

C++ kmp算法模板代码示例:

 

 
 
 
  1. template < class T,class TL>   
  2. inline int kmpmatch(const T *source,TL sourceLen,
    const T *pattern,TL patternLen)   
  3. {   
  4. vector< int> next;   
  5. for ( int i = 0; i <  patternLen ; i ++ )   
  6. next.push_back(0);   
  7. next[0] = -1;   
  8. for( int i = 1 ; i <  patternLen ; i ++ )   
  9. {   
  10. int j = next[i - 1];   
  11. while ( (pattern[i] != pattern[i + 1])&& (j >= 0))   
  12. {   
  13. j = next[j];   
  14. }   
  15. if ( pattern[i] == pattern[j + 1])   
  16. {   
  17. next[i] = j + 1;   
  18. }   
  19. else   
  20. {   
  21. next[i] = -1;   
  22. }   
  23. }   
  24. int i = 0;   
  25. int j = 0;   
  26. while (( i <  sourceLen ) && ( j <  patternLen ))   
  27. {   
  28. if ( source[i] == pattern[j] )   
  29. {   
  30. i ++;   
  31. j ++;   
  32. }   
  33. else if ( j == 0 )   
  34. {   
  35. i ++;   
  36. }   
  37. else   
  38. {   
  39. j = next[j - 1 ] + 1;   
  40. }   
  41. }   
  42. if ( j >= patternLen )   
  43. {   
  44. if ( !next.empty() )   
  45. next.clear();   
  46. return i - patternLen ;   
  47. }   
  48. else   
  49. {   
  50. if ( !next.empty() )   
  51. next.clear();   
  52. return -1;   
  53. }   

 

以上就是对C++ kmp算法模板的相关介绍。

THE END