problem Implement strStr code class Solution { public: int strStr(string haystack, string needle) { if(needle.size()==0) return 0; if( (haystack.size()==0) || (haystack.size()needle.size()) ) return -1; int index = -1; size_t le
problem
Implement strStr
code
class Solution {public:
int strStr(string haystack, string needle) {
if(needle.size()==0) return 0;
if( (haystack.size()==0) || (haystack.size()<needle.size()) ) return -1;
int index = -1;
size_t len = haystack.size() - needle.size();
for(size_t i=0; i<len+1; i++)
{
if(haystack[i]!=needle[0]) continue;
size_t j = 1;
for( ; j<needle.size(); )
{
if(haystack[i+j]!=needle[j]) break;
j++;
}
if(j==needle.size()) { index = i; break;}//
}
return index;
}
};
View Code
注意,
1.需要考虑特殊情况以及异常点;
2.获取第一个的index,所以得到一个结果就直接退出外层循环;
参考
1.leetcode;
完