class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.size()==0)
return 0;
if(needle.size()>haystack.size())
return -1;
if(haystack.size()==needle.size())
{
if( haystack.compare(needle)==0)
return 0;
else
return -1;
}
int index = 0;
int i;
for(i = 0 ; i < haystack.size()-needle.size()+1;i++)
{
if(haystack[i]==needle[0])
{
index = i;
int j = 1;
while(j < needle.size())
{
if(haystack[i+j]==needle[j])
j++;
else
break;
}
if(j == needle.size())
return index;
}
}
if(i == haystack.size()-needle.size()+1)
return -1;
}
};
易错点:
if(needle.size()==0)
return 0;
网友评论