next数组的理解

来源:互联网 发布:学会python能干嘛 编辑:程序博客网 时间:2024/05/16 10:57
// next.cpp : 定义控制台应用程序的入口点。
//KMP next数组
//前缀数组(next数组)表示字符串的最长匹配前后缀
//字符串开始到当前位置的子串


#include "stdafx.h"
#include <stdio.h>

int next[50];
int GetNextArr(const char* str, int nLength)
{

    //nLength 字符串长度
    next[0] = 0;  //字符串为以为时为0 前后缀均为字符串的真子串不能包含自身
    for(int i = 1; i < nLength; i++)
    {
        //如何确定下一个next【i】的值 当我们知道next[0...i-1];
        //可以知道如果next[i-1]等于一个值m 表示有m个字符是匹配的 如果当str[i]和str[m]一样 那么next[i] = m + 1;
        //如果str[i] != str[m] 后面该怎么办 我们的目标是找到末尾是str[i]的最长匹配前后缀 如果str【i】 != str[m]
        //那么下一步也是将str【i】 与 哪一个比较
        //理解下发现下一个比较 next[m-1] 因为m的个不匹配 说明前面m-1个肯定是一样的
        int nTemp = next[i-1];    
        while(nTemp >= 0)
        {
            if(nTemp == 0)
            {
                if(str[i] == str[0])
                {
                    next[i] = 1;
                }
                else
                {
                    next[i] = 0;
                }
                
                break;
            }
            
            if(str[i] == str[nTemp])
            {
                next[i] = nTemp + 1;
                break;
            }
            
            nTemp = next[nTemp - 1];
        }
    }
    
    return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{

    char str[17] = "agctagcagctagctg";
    GetNextArr(str, 16);
    for(int i = 0; i < 16; i++)
    printf("%d ", next[i]);
    return 0;
}

0 0
原创粉丝点击