题目描述:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
这道题为easy难度,所以对时间复杂度要求不高,可以直接用暴力的方法解决,即先在haystack中匹配needle的第一个字符,如果匹配就比较余下的字符是否匹配。
同时要先考虑needle为空的情况,因为当needle为空,它和任何字符串都匹配,所以返回值为0。
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.size()==0) return 0;
for(int i=0;i<haystack.size();i++)
{
if(haystack[i]==needle[0])
{
if(haystack.substr(i,needle.length())==needle)
return i;
}
}
return -1;
}
};