KMP算法

来源:互联网 发布:python 每秒执行一次 编辑:程序博客网 时间:2024/05/01 03:29

今天把放了一年多都没有看过的模式匹配算法又拿出来复习了一下,顺便在这里留点记号。

 

void get_next(char * str, int len, int nextVal[])
{
    
int i = 0;
    
int j = -1;
    nextVal[
0= -1;

    
while( i < len )
    
{
        
if( j == -1 || str[i] == str[j] )
        
{
            i
++;
            j
++;
            nextVal[i] 
= j;
        }

        
else
        
{
            j 
= nextVal[j];
        }

    }

}
    

下面是记过修正后的算法:

 

void get_nextEx(char * str, int len, int nextVal[])
{
    
int i = 0;
    
int j = -1;
    nextVal[
0= -1;

    
while( i < len )
    
{
        
if( j == -1 || str[i] == str[j] )
        
{
            i
++;
            j
++;
            
if( str[i] != str[j] )
            
{
                nextVal[i] 
= j;
            }

            
else
            
{
                nextVal[i] 
= nextVal[j];
            }

        }

        
else
        
{
            j 
= nextVal[j];
        }

    }

}


原创粉丝点击