首页 > 其他 > 详细

Implement strStr()

时间:2015-08-31 21:38:51      阅读:237      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!