生活随笔
收集整理的這篇文章主要介紹了
匹配串 KMP算法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
匹配串---基礎寫法 :
#include <stdio.h>
#include <string.h> //庫函數
/*char * strstr(char *string, char *pattern);
*/
typedef char* Position; //重命名
#define NotFound NULLint main()
{char string[] = "This is a simple example.";char pattern[] = "simple";Position p = strstr(string, pattern);printf("%s\n", p);return 0;
}
KMP算法 :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>typedef int Position; //起別名
#define NotFound -1 //定義一個不可能是下標的量void BuildMatch(char *pattern, int *match)
{Position i, j;int m = strlen(pattern);match[0] = -1;for (j = 1; j < m; j++){i = match[j - 1];while ((i >= 0) && (pattern[i + 1] != pattern[j]))i = match[i];if (pattern[i + 1] == pattern[j])match[j] = i + 1;elsematch[j] = -1;}
}Position KMP(char *string, char *pattern)
{int n = strlen(string);int m = strlen(pattern);Position s, p, *match;if (n < m)return NotFound;match = (Position *)malloc(sizeof(Position) * m);BuildMatch(pattern, match);s = p = 0;while (s < n && p < m){if (string[s] == pattern[p]){s++;p++;}else if (p > 0)p = match[p - 1] + 1;elses++;}return (p == m) ? (s - m) : NotFound;
}int main()
{//char string[] = "This is a simple example.";//char pattern[] = "sample";printf("請輸入字符串1 :\n");char string[81];// scanf("%s",string);gets(string);//getchar();printf("請輸入字符串2 :\n");char pattern[81];//scanf("%s",pattern);gets(pattern);//返回字符指針,只能處理字符串;返回數組下標,可處理任何類型串Position p = KMP(string, pattern); //返回數組下標if (p == NotFound)printf("NotFound.\n");elseprintf("字符串匹配成功:%s\n", string + p);return 0;
}
總結
以上是生活随笔為你收集整理的匹配串 KMP算法的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。