您的位置:首页 > 其它

[leetcode]: 28. Implement strStr()

2017-06-18 17:23 357 查看

1.题目

Implement strStr().

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

手动实现strStr()函数,返回子字符串needle在字符串haystack中第一次出现的位置

2.分析

暂时还没去学习KMP,所以就手动遍历匹配字符串了。

3.代码

class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.size()==0)
return 0;
if (haystack.size()<needle.size())
return -1;
for (int i = 0; i <= haystack.size() - needle.size(); i++) {
int j = 0;
while (j<needle.size() && haystack[i + j] == needle[j])
++j;
if (j == needle.size())
return i;
}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode strStr