分析:找haystack里面有没有needle,有就返回子串起始位置,没有就返回-1,若needle是空串就返回0
用C++调用string.find(string)的代码如下,很容易写,但是效率。。可以说是很低。
class Solution
{
public:
int strStr(string haystack, string needle)
{
if(needle.empty())
return 0;
return haystack.find(needle);
}
};//Runtime: 12 ms, Memory Usage: 9.2 MB
然后就自己模拟了一个过程,如下:
class Solution
{
public:
int strStr(string haystack, string needle)
{
if(needle.empty())
return 0;
int res=-1,idx=0;
for(int i=0; haystack[i]!='\0'; i++)
{
if((i+needle.length())>haystack.length())
return -1;
int t=i;
while(haystack[t]==needle[idx])
{
if(t<haystack.length() && idx<needle.length())
{
idx++;
t++;
}
else
break;
}
if(t-i==needle.length())
return i;
else
idx=0;
}
return res;
}
};//Runtime: 4 ms, Memory Usage: 8.9 MB
这下运行就快多了,果然还是得自己写呀。。。
如果有路过的朋友知道更快的方法,拜托一定要在评论区留言呀~谢谢!!