码迷,mamicode.com
首页 > 其他好文 > 详细

Implement strStr()

时间:2015-08-31 21:40:20      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

Description:

Implement strStr().

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

Code:

vector<int> getNext ( string&t  )
{
    size_t n = t.length();
    vector<int>next(n,-1);

    int i = 0, j = -1;
    while ( i < n-1 )
    {
        if ( j == -1 || t[i] == t[j])
        {
            ++i;
            ++j;
            next[i] = j;
        }
        else
            j = next[j];
    }
    for (int i = 0; i < next.size(); ++i)
        cout << next[i];
    cout << endl;
    return next;
}
int indexKMP( string& t, string&w, vector<int>& next )
{
    int i = 0, j = 0;
    int lengthT = t.length();
    int lengthW = w.length();

    while ( i < lengthT && j < lengthW )
    {
        if ( j == -1 || t[i] == w[j] )         //继续比较后继字符
        {
            ++i;
            ++j;
        }
        else
            j = next[j];
    }
    if ( j == lengthW )
        return i - lengthW;
    else
        return -1;
}
    int strStr(string haystack, string needle) {
        if (needle == "")
            return 0;
        if (haystack == "")
            return -1;
     vector<int>next;
     next = getNext(needle);
      return indexKMP(haystack,needle,next);
       return -1;
    }

 

Implement strStr()

标签:

原文地址:http://www.cnblogs.com/happygirl-zjj/p/4774034.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!