首页 > 其他 > 详细

leetcode笔记:Implement strStr()

时间:2015-10-10 00:27:52      阅读:208      评论:0      收藏:0      [点我收藏+]

一.题目描述

Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

二.题目分析

实现strstr()函数。返回needle(关键字)在haystack(字符串)中第一次出现的位置,如果needle不在haystack中,则返回-1。由于使用暴力方法的时间复杂度为O(mn)会超时,可使用著名的KMP算法解决。该是由Knuth,Morris,Pratt共同提出的字符串匹配算法,其对于任何字符串和目标字符串,都可以在线性时间内完成匹配查找,是一个非常优秀的字符串匹配算法。

三.示例代码

KMP算法:

class Solution {
public:
    void getNext(vector<int> &next, string &needle) {
        int i = 0, j = -1;
        next[i] = j;
        while (i != needle.length()) {
            while (j != -1 && needle[i] != needle[j]) j = next[j];
            next[++i] = ++j;
        }
    }
    int strStr(string haystack, string needle) {
        if (haystack.empty()) return needle.empty() ? 0 : -1;
        if (needle.empty()) return 0;
        vector<int> next(needle.length() + 1);
        getNext(next, needle);
        int i = 0, j = 0;
        while (i != haystack.length()) {
            while (j != -1 && haystack[i] != needle[j]) j = next[j];
            ++i; ++j;
            if (j == needle.length()) return i - j;
        }
        return -1;
    }
};

四.小结

对于这题,还有其他一些有名的算法,如Rabin-Karp和Boyer-Moore算法。

版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode笔记:Implement strStr()

原文:http://blog.csdn.net/liyuefeilong/article/details/49010291

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