LeetCode:Implement strStr()

problem:

Implement strStr().

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

此题目实质为字符串匹配问题,其中比较高效的算法是KMP算法 它相对于暴力破解算法比较成功的找到了有效的回溯位置。

解法一:暴力破解

 1 class Solution {
 2 public:
 3     int strStr(string haystack, string needle) {
 4         int slen=haystack.size();
 5         int plen=needle.size();
 6         
 7         int i=0;
 8         int j=0;
 9         for(;i<slen&&j<plen;)
10         {
11             if(haystack[i]==needle[j])
12             {
13                 i++;j++;
14             }
15             else{   //匹配不成功回溯  j重置
16                 i=i-j+1;
17                 j=0;
18             }
19         }
20         if(j==plen)
21            return i-j;
22          else
23           return -1;
24     }
25 };

 解法二:kmp

 1 class Solution {
 2 public:
 3     int strStr(string s, string p) {
 4         //kmp算法
 5         
 6         if(!p.size()||!s.size()) return 0;
 7         vector<int> next(p.size(),0);
 8         int plen=p.size();
 9         int slen=s.size();
10         computeNext(next,p,plen);
11         int j;int i;
12         for(i=0;i<slen;i++)
13             for(j=0;j<plen;j++)
14             {
15                 if(s[i]==p[j])
16                 {
17                     i++;j++;
18                 }
19                 else{
20                     j=next[j];
21                 }
22                 
23             }
24           if(j==plen) return i-j;
25           else return -1;
26         
27     }
28     
29     
30     void computeNext(vector<int> &next,string &p,int &plen)
31     {
32         
33         int q=next[0]=-1;
34         
35         int j=0;
36         plen--;
37         while(j<plen)
38         {
39             if(q==-1||p[q]==p[j])
40                 next[++j]=++q;
41             else 
42                 q=next[q];
43             
44         }
45     }
46     
47 };

          

原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4556148.html