就写个简单的吧
class Solution {
public:
int strStr(string haystack, string needle) {
int len=needle.size(),i,n=haystack.size();
if(len==0)
return 0;
for(i=0;i<=n-len;i++)
{
string target(haystack.begin()+i,haystack.begin()+i+len);
if(target==needle)
return i;
}
return -1;
}
};
注意两点
1.如题目所说,若needle为空,则返回0。
2.对string类参数为迭代器的构造函数,可以理解为半开半闭区间,含头不含尾。