您的位置:首页 > 其它

Implement strStr() leetcode

2015-10-21 00:08 274 查看
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。注意边界条件!!

  我的源代码如下:

class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty())
return 0;
if (haystack.empty())
{
if(!needle.empty())
return -1;
}
if(needle.size()>haystack.size())
return -1;
int index = 0, reset = -1;
while (index < haystack.size())
{
if (haystack[index] != needle[0])
{
index++;
continue;
}
reset = index + 1;
int i;
for ( i = 1;index+needle.size()<=haystack.size()&& i < needle.size(); ++i)
{
if (haystack[index + i] != needle[i])
break;
}
if (i == needle.size())
return index ;
else index = reset;
}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: