首页 > 编程语言 > 详细

KMP算法(思路未补)

时间:2020-07-02 23:05:42      阅读:78      评论:0      收藏:0      [点我收藏+]
 1 #include <stdio.h>
 2 #include <string.h> 
 3 #include <stdlib.h>
 4 
 5 typedef int Position;
 6 #define NotFound -1
 7 
 8 void BuildMatch(char* pattern, int* match)
 9 {
10     Position i, j;
11     int m = strlen(pattern);
12     match[0] = -1;
13 
14     for (j = 1; j < m; j++) {
15         i = match[j - 1];
16         while ((i >= 0) && (pattern[i + 1] != pattern[j]))
17             i = match[i];
18         if (pattern[i + 1] == pattern[j])
19             match[j] = i + 1;
20         else match[j] = -1;
21     }
22 }
23 
24 Position KMP(char* string, char* pattern)
25 {
26     int n = strlen(string);
27     int m = strlen(pattern);
28     Position s, p, * match;
29 
30     if (n < m) return NotFound;
31     match = (Position*)malloc(sizeof(Position) * m);
32     BuildMatch(pattern, match);
33     s = p = 0;
34     while (s < n && p < m) {
35         if (string[s] == pattern[p]) {
36             s++; p++;
37         }
38         else if (p > 0) p = match[p - 1] + 1;
39         else s++;
40     }
41     return (p == m) ? (s - m) : NotFound;
42 }
43 
44 int main()
45 {
46     char string[] = "This is a simple example.";
47     char pattern[] = "simple";
48     Position p = KMP(string, pattern);
49     if (p == NotFound) printf("Not Found.\n");
50     else printf("%s\n", string + p);
51     return 0;
52 }

 

KMP算法(思路未补)

原文:https://www.cnblogs.com/letianpaiai/p/13227575.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!