首页 > 其他 > 详细

28. Implement strStr()

时间:2017-10-26 11:24:36      阅读:278      评论:0      收藏:0      [点我收藏+]

Implement strStr().

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

 

判断子串needle 在主串haystack中首次出现的位置

 

C++(6ms):   KMP算法

 1 class Solution {
 2 public:
 3     vector<int> getNext(string needle , int tlen){
 4         int j, k;
 5         vector<int> Next(tlen+1, 0);
 6         j = 0; k = -1; Next[0] = -1;
 7         while(j < tlen)
 8             if(k == -1 || needle[j] == needle[k])
 9                 Next[++j] = ++k;
10             else
11                 k = Next[k];
12         return Next ;
13     }
14     
15     int strStr(string haystack, string needle) {
16         int slen = haystack.size() ;
17         int tlen = needle.size() ;
18         if (!tlen)
19             return 0 ;
20         vector<int> Next = getNext(needle,tlen) ;
21         int i = 0, j = 0;
22         while(i < slen && j < tlen)
23         {
24             if(j == -1 || haystack[i] == needle[j])
25             {
26                 i++; j++;
27             }
28             else
29                 j = Next[j];
30         }
31         if(j == tlen)
32             return i - tlen ;
33         else
34             return -1;
35     }
36 };

 

28. Implement strStr()

原文:http://www.cnblogs.com/mengchunchen/p/7735619.html

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