28. Implement strStr()

来源:互联网 发布:科伊桑人,知乎 编辑:程序博客网 时间:2024/05/18 02:59

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算法(看毛片算法),思想大致明白了,但是实现不容易。有时间可以了解 下如何代码实现。

0 0
原创粉丝点击