您的位置:首页 > 其它

28. Implement strStr()

2016-05-16 00:29 357 查看
1.Question

Implement strStr().

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

class Solution {
public:
int strStr(string haystack, string needle) {
int sizeofneedle = needle.size();
for(int i = 0, size = haystack.size() - needle.size() +  1; i < size; i++)
{
if(haystack.substr(i, sizeofneedle) == needle) return i;
}
return -1;
}
};
3.Note

a. 字符串string的比较可以直接用 == 。也可以是.campare。

b. 针对这个问题有个更高效的知名算法, 称为KMP算法(看毛片算法),思想大致明白了,但是实现不容易。有时间可以了解 下如何代码实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: