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
本文出自 “做最好的自己” 博客,请务必保留此出处http://qiaopeng688.blog.51cto.com/3572484/1836727
leetCode 28. Implement strStr() 字符串
原文:http://qiaopeng688.blog.51cto.com/3572484/1836727