关闭

Implement strStr()

标签: Two PointersString
123人阅读 评论(0) 收藏 举报
分类:

Implement strStr().

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

Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button to reset your code definition.


Solution:

class Solution {
public:
    void getNext(string needle, vector<int> &next)
    {
        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) {
        vector<int> next(needle.length()+1);
        getNext(needle, next);
        int i = 0, j = 0;
        int hlen = haystack.length();
        int nlen = needle.length();
        while(i < hlen && j < nlen)
        {
            if(j == -1 || haystack[i] == needle[j])
            {
                ++i;
                ++j;
            }
            else
            {
                j = next[j];
            }
        }
        if(j == nlen) return i - j;
        else return -1;
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:21203次
    • 积分:1673
    • 等级:
    • 排名:千里之外
    • 原创:152篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类