题目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
分析: 没有太多可说的,easy难度的一道题目,使用暴力搜索的方法即可通过 。
当然也可以采用更高级的算法,比如KMP。
代码:
c++
class Solution
{
public:
int strStr(string haystack, string needle)
{
int hlen = haystack.size();
int nlen = needle.size();
if (hlen < nlen )
return -1;
if(nlen == 0)
return 0;
int i,j;
for (i = 0; i < (hlen - nlen + 1); i++)
{
for (j =0; j < nlen; j++)
{
if (haystack[i+j] != needle[j])
break;
}
if(j == nlen)
{
return i;
}
}
return -1;
}
};