leetcode 28

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.

子串匹配问题,KMP忘了个干净~~  费了点劲终于完成了。

个人感觉是比较乱,对边界把握还是不准,提交了很多次才通过。

代码如下:

 1 class Solution {
 2 public:
 3     int strStr(string haystack, string needle) {
 4         if(haystack.length() == 0 || needle.length() == 0 || haystack.length() < needle.length())
 5         {
 6             if(haystack.length() == 0 && needle.length() == 0)
 7             {
 8                 return 0;
 9             }
10             if(haystack.length() != 0 && needle.length() == 0)
11             {
12                 return 0;
13             }
14             return -1;
15         }
16         int n = haystack.length();
17         int m = needle.length();
18         int index = 0;
19         int j=0;
20         for(int i=0; i<n; i++)
21         {
22              if(haystack[i] == needle[j])
23              {
24                  j++;
25                  index = i;
26                  if(j == m)
27                  {
28                     return index-m+1;
29                  }
30              }
31              else
32              {
33                  i = i -j;
34                  j=0;
35              }
36              
37         }
38         return -1;
39     }
40 };

100%~有点不科学~~~~

原文地址:https://www.cnblogs.com/shellfishsplace/p/5851188.html