您的位置:首页 > 其它

leetcode 28. Implement strStr() 实现strStr()函数

2017-04-12 16:24 573 查看
Implement strStr().

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

思路:分别求出两个字符串的长度,如果母字符串的长度小于子字符串,则返回-1;如果母字符中有与子字符串,则返回母字符的起始位置。
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
int m=haystack.size(),n=needle.size();
if(m<n) return -1;
for(int i=0;i<=m-n;++i){
int j;
for(j=0;j<n;++j){
if(haystack[i+j]!=needle[j]) break;
}
if(j==n) return i;  // 返回起始位置
}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: