首页 > 技术文章 > Implement strStr() leetcode

chess 2015-10-21 00:08 原文

Implement strStr().

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

Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.

 

解题:我用的方法相当于暴力破解:int strStr(string haystack, string needle) ;

  首先,遍历haystack,依次寻找第一个与needle第一个字符匹配的位置,同时记录相对于该位置的下一个位置(我记为ret,一旦接下来的匹配不成功,重新遍历haystack时,就从ret开始),如果遍历完haystack都没匹配成功,则返回-1。注意边界条件!!

  我的源代码如下:

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

 

推荐阅读