欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

串的模式匹配算法

程序员文章站 2022-07-15 08:54:29
...
串的模式匹配算法
#include <cstdlib>
#include <iostream>
#include <string>
#define  MaxSize 15
 
using namespace std;
int next[9],nextval[9];


int KMPIndex(string S, int start,string T, int next[ ]) 
{
    //利用模式串T的next函数求T在主串S第pos个字符之后的位置 
    // 的KMP算法。其中,T非空,1<=pos<=S.length;
     
      int i=start,j=1,v;
    
      while ( i<=S.length()&&j<=T.length()) {
            
           if (j==0|| S[i] == T[j] ) 
           {
               ++i;  ++j; //继续比较后继字符 
                
           }   
           
           else j=next[j]; //模式串向右移动         
          
         }
     
        if(j>T.length()) v=i-T.length();  //匹配成功 
   
            else    v=0;    //匹配不成功 
              
    return v;
}
  
void GetNext(string T)
  {  	
        //球模式串T的next函数值并存入数组next 
        int i = 1, j = 0;  next[1] = 0;
        
    	while(i< T.size()){
                 
		   if(j==0 ||T[i]==T[j])
		   
		      {++i; ++j; next[i]=j;	}
	        
         else j=next[j]; 
         
	   }                 
   }
void GetNextval(string T)
  {  	
        //球模式串T的next函数值并存入数组nextval 
        int i = 1, j = 0;  next[1] = 0;
        
    	while(i< T.size()){
                 
		   if(j==0 ||T[i]==T[j])
		      {
                   ++i; ++j; 
                  if (T[i]!=T[j]) nextval[i]=j;
                  
                   else nextval[i]=nextval[j];	
              }
	        
         else j=nextval[j]; 
         
	   }                 
   }   
//主函数 
int main(void)
{      
        string S="acabaabaabcacaabc", T ="3abaabcac";   
        int pos; 
        printf("调用GetNext得到的next数组元素"); 
        GetNext(T);
        for(int i=1;i<9;i++){                      
              printf("next=%d\n",next[i]);            
       } 
       printf("调用GetNextval得到的nextval数组元素"); 
        GetNextval(T);
         for(int i=1;i<9;i++){                      
              printf("next=%d\n",nextval[i]);            
       }                   
    	pos = KMPIndex(S, 1, T, next);       
        printf("pos = %d\n", pos);     
        system("PAUSE");
    return EXIT_SUCCESS;
}
 

结果:


串的模式匹配算法
            
    
    博客分类: C++   KMP   数据结构 算法 C++   KMP   数据结构 算法 
 

  • 串的模式匹配算法
            
    
    博客分类: C++   KMP   数据结构 算法 C++   KMP   数据结构 算法 
  • 大小: 8.4 KB