我写的:
class Solution {
public:
int strStr(string haystack, string needle) {
int hsize = haystack.size();
int nsize = needle.size();
if(hsize < nsize)
return -1;
if(nsize == 0)
return 0;
for(int i = 0; i <= hsize - nsize; ++i)
{
if(haystack[i] == needle[0])
{
int start = 0;
while(start < nsize)
{
if(haystack[start + i] != needle[start])
break;
else
start++;
}
if(start == nsize)
return i;
}
}
return -1;
}
};
别人的简单代码:
class Solution {
public:
int strStr(string haystack, string needle) {
for(int i = 0;; ++i)
{
for(int j = 0;; ++j)
{
if(j == needle.size())
return i;
if(i + j == haystack.size())
return -1;
if(needle[j] != haystack[i + j])
break;
}
}
}
};
省去了很多判断过程。