您的位置:首页 > 其它

leetCode 28. Implement strStr() 字符串

2016-08-11 01:03 330 查看
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.

在haystack中找与needle 第一个相匹配的位置。如果找不到,返回-1。
代码如下:
class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack.size() == 0 && needle.size() == 0)
return 0;
if(needle.size() == 0)
return 0;
if(haystack.size() < needle.size())
return -1;
for(int i = 0;i < haystack.size() - needle.size() + 1;i++)
{
bool flag = true;
if(needle[0] == haystack[i])
{
int j = 0;
for(; j < needle.size();j++)
{
if(needle[j] != haystack[i+j])
{
flag = false;
break;
}

}
if(flag)
return i;
}
}
return -1;
}
};
2016-08-11 01:02:49
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字符串