面试题30:KMP 字符串查找

参考:http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html
自己写的很简单的KMP字符串匹配
 1 int KMP(string s,string p){
 2     int pLen = p.length();
 3     int* next = new int[pLen];
 4     next[0] = -1;
 5 
 6     int k = -1;
 7     int j = 0;
 8     while(j < pLen - 1){
 9         if(k == -1 || p[k] == p[j]){
10             k++;
11             j++;
12             next[j] = k;
13         }else{
14             k = next[k];
15         }
16     }
17 
18     //print next array;
19     for(int k=0;k<pLen;k++){
20         std::cout << next[k]<< ",";
21     }
22     std::cout << std::endl;
23 
24     j = 0;
25     size_t i = 0;
26     size_t sLen = s.length();
27     while(i<sLen && j < pLen){
28         if(j == -1 || s[i] == p[j]){
29             i++;
30             j++;
31         }else{
32             j = next[j];
33         }
34     }
35 
36     delete next;
37     if(j == pLen){
38         return i - j;
39     }else{
40         return -1;
41     }
42 }

 

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

 1 class Solution {
 2 public:
 3     char *strStr(char *haystack, char *needle) {
 4         if(haystack == nullptr || needle == nullptr) return nullptr;
 5 
 6         int i = 0,j =0;
 7         int start = 0;
 8         while(haystack[i] != '\0' && needle[j] != '\0'){
 9             if(haystack[i] == needle[j]){
10                 i++;
11                 j++;
12             }else{
13                 start++;
14                 i = start;
15                 j = 0;
16             }
17         }
18         if(needle[j] == '\0') return haystack+start;
19         else return nullptr;
20     }
21 };

 

posted @ 2017-05-21 16:09  wxquare  阅读(486)  评论(0编辑  收藏  举报