LeetCode OJ 之 Implement strStr() (在字符串中查找字符串)

来源:互联网 发布:阿桑奇曝光中国知乎 编辑:程序博客网 时间:2024/05/16 05:09

题目:

Implement strStr().

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

在字符串haystack中查找字符串needle,如果找到,返回在haystack中首次出现的下标,否则返回-1.

思路:

暴力算法的复杂度是O ( m ∗ n ),代码如下。更高效的的算法有 KMP 算法、Boyer-Mooer 算法和Rabin-Karp 算法。

代码:

1、暴力解法

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

2、KMP算法参考:http://blog.csdn.net/u012243115/article/details/41868933 。

代码:

class Solution {public:    int strStr(string haystack, string needle)     {        if(needle.empty())             return 0;        int len1 = haystack.size();        int len2 = needle.size();        vector<int> next(len2 , 0);        next[0] = -1;        int j = 0, k = -1;                //求needle的next数组        while(j < len2-1)         {            if(k == -1 || needle[j] == needle[k])             {                ++k;                ++j;                next[j] = k;            }            else             {                k = next[k];            }        }                int i = 0, jt = 0;        while(i < len1 && jt < len2)         {            if(haystack[i] == needle[jt])             {                ++i;                ++jt;            }            else             {                jt = next[jt];                if(jt == -1)                {                    jt = 0;                    i++;                }            }        }                if(jt == len2)             return i-jt;        else             return -1;    }};





0 0