首页 > 其他 > 详细

【LeetCode】28. Implement strStr()

时间:2015-08-28 10:48:34      阅读:115      评论:0      收藏:0      [点我收藏+]

题目:

Implement strStr().

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

提示:

此题可以使用暴力搜索方法。当然也可以使用其他一些高级方法,如:Rabin-Karp, KMP等等。这些算法打算等之后对他们更了解了以后,单独写一些文章对其总结。因此这里仅给出暴力搜索方法。

代码:

class Solution {
public:
    int strStr(string haystack, string needle) {
    int hay_len = haystack.size();
    int needle_len = needle.size();
    if (needle_len == 0) return 0;
    if (hay_len == 0) return -1; 
    int i = 0, j = 0, p;
    for (i = 0; i <= hay_len - needle_len; ++i) {
        for (p = i, j = 0; j < needle_len; ++j, ++p) {
            if (haystack[p] != needle[j]) break;
        }
        if (j == needle_len) return i;
    }
    return -1;
}
};

【LeetCode】28. Implement strStr()

原文:http://www.cnblogs.com/jdneo/p/4765748.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!