KMP算法原理與實現(精簡)

jopen 9年前發布 | 3K 次閱讀 C/C++ 算法

思想:使源字符串中的下標不回溯,利用模式字符串自身的相關性,減少模式字符串中下標回溯的距離。從而減少比較的次數。

關鍵問題: 分析模式字符串,得出 部分匹配值數組。

原理參考此處

具體實現:

#include <stdio.h>
#include <string.h>
#include <malloc.h>

void get_next(int next[], char source[], int n);//獲取部分匹配字符數組
int Index_KMP(char* s_string, char* t_string, int pos);//返回源字符串s_string中pos開始 與t_string匹配的第一個字符串首字母下標,無匹配返回0

int main()
{
    char *source_str = "BBC ABCDAB ABCDABCDABDE";
    char *t_str = "ABCDAB";//模式串

    printf("%d\n", Index_KMP(source_str, t_str, 8));

    return 0;
}

void get_next(int next[], char source[], int n)
{
    int i = 0;
    next[0] = 0;
    for(i = 1; i < n; i++)
    {
        if(source[i] == source[next[i-1]])
            next[i] = next[i-1] + 1;
        else
            next[i] = 0;
    }
}

int Index_KMP(char* s_string, char* t_string, int pos)
{
    int i = pos;//指向 s_string的起始下標
    int j = 0;//指向 t_string的起始下標
    int t_len = strlen(t_string);
    int s_len = strlen(s_string);
    int* t_next = (int*)malloc(sizeof(int)*t_len);
    int m;

    get_next(t_next, t_string, t_len);//獲取t_string的部分匹配字符數組
    for(m = 0; m < t_len; m++)
        printf("%d ",t_next[m]);
    printf("\n");

    while( (i<s_len)&&(j<t_len) )
    {
        if(s_string[i] == t_string[j])
        {
            i++;
            j++;
        }
        else
        {
            if(j == 0)
            {
                i++; //源字符串下表前移動
            }
            else
            {
                m = j - t_next[j-1];//需回溯的位數
                j = j - m;//設置下一次的起始坐標   
            }
        }
   }
    free(t_next);

    if(j==t_len)
        return i-t_len;
    else
        return 0;
}

來自:http://blog.csdn.net/youxin2012/article/details/17083261

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!