晨太狼之狼堡

二货一枚快乐多

Implement strStr()

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;
    }
};


阅读更多
文章标签: Two Pointers String
个人分类: LeetCode
上一篇Count and Say
下一篇Anagrams
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭