28. Implement strStr()

28. Implement strStr()

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

 1 /**
 2  * @param {string} haystack
 3  * @param {string} needle
 4  * @return {number}
 5  */
 6 var strStr = function(haystack, needle) {
 7     //题目是想求needle是不是haystack是子串。是的话返回开始匹配的index,否者就返回-1
 8     
 9     //暴力的写法就是全部都试过一边,不过kmp是比较好的实现方式
10     //kmp算法最难的是next表的建立
11     
12     function next(pattern){
13         
14         var next = [];        
15         var len = pattern.length; 
16         next[0] = -1;
17         
18         var k = -1;
19         var j = 0;
20         
21         while(j < len-1){
22             
23             //此刻,k即next[j-1],且pattern[k]表示前缀,pattern[j]表示后缀
24             //注:k==-1表示未找到k前缀和k后缀相等,首次分析可先忽略
25             
26             if(k == -1 || pattern[j] == pattern[k]){            
27                 ++j;
28                 ++k;
29                 next[j] = k;
30             }else{  //pattern[j] 与 pattern[k]不相等,则继续递归计算前缀p[next[k]]
31                 
32                 k = next[k];
33             }
34             
35         }
36         return next;
37     }
38     
39     var next = next(needle);
40     
41     var i = 0,j = 0;
42     
43     while(i < haystack.length && j < needle.length){
44         
45        //当j=-1时,要移动的是i,当然j也要归0
46         if(j == -1 || haystack[i] == needle[j]){
47             
48             i++;
49             j++;
50             
51         }else{
52             
53             //i不需要回溯了
54             //i = i - j +  1;
55             
56             j = next[j]; //j回到指定位置
57         
58         }
59         
60     }
61     
62     if(j == needle.length){
63         
64         return i - j;
65         
66     }else{
67         
68         return -1;
69     }
70     
71 };

 

posted @ 2017-10-18 17:11  hdu胡恩超  阅读(164)  评论(0编辑  收藏  举报