zhengdy

Code in Tokyo

2010年5月17日 #

KMP算法

 

 1 int kmpstrstr(const char *text, const char *pattern) {   
 2     const int Pattern_Max = 256;   
 3     static unsigned char next[Pattern_Max];   
 4     int i, j;   
 5     int len = strlen(pattern);   
 6   
 7     if (len <= 0 || len > Pattern_Max) { return -1; }   
 8     i = 1;  j = 0;  next[1= 0;   
 9     while (pattern[i]) {   
10         if (pattern[i] == pattern[j]) { next[++i] = ++j; } else  
11         if (j == 0)                   { next[++i] = j;   } else  
12                                       { j = next[j];     }   
13     }   
14     i = j = 0;   
15     while (text[i] && pattern[j]) {   
16         if (text[i] == pattern[j]) { i++;  j++;   } else  
17         if (j == 0)                { i++;         } else  
18                                    { j = next[j]; }    
19     }   
20     return (pattern[j] ? -1 : (i-j));   
21 }

posted @ 2010-05-17 16:56 Code in Tokyo 阅读(189) | 评论 (0)编辑 收藏

仅列出标题