您的位置:首页 > 其它

28. Implement strStr()

2016-02-21 16:56 393 查看
Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Solution:

class Solution {
public:
int strStr(string haystack, string needle) {
int sz1 = haystack.size();
int sz2 = needle.size();
if(sz1<sz2) return -1;
else if(sz1==0||sz2==0) return 0;
else {
for(int i=0;i<sz1-sz2+1;i++){
if(haystack[i]==needle[0]){
string tmp = haystack.substr(i,sz2);
if(tmp==needle) return i;
}
}
return -1;
}

}
};
心得:问题比较简单,注意空集的情况返回0这个corner就行

运行速度:快
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: