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

[LeetCode] Implement strStr()

时间:2018-03-11 17:10:15      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:else   log   size   www   art   example   ret   www.   amp   

Implement strStr().

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

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

 

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

使用KMP算法来overwrite strStr()

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.empty()) return 0;
        if(haystack.empty()) return -1;
        return kmp(haystack, needle);
    }
    
    int kmp(string haystack, string needle)
    {
        vector<int> next = getNext(needle); 
        int sLen = haystack.size(), tLen = needle.size();
        int i = 0, j = 0, res = -1;
        while (i < sLen)
        {
            if (j == -1 || haystack[i] == needle[j])
            {
                ++i;
                ++j;
            }
            else
            {
                j = next[j];
            }
            if (j == tLen)
            {
                res = i - tLen;
                break;
            }
        }
        return res;
    }
    
    vector<int> getNext(string needle)
    {
        vector<int> next(needle.size(), -1);
        int tLen = needle.size();
        int i = 0, j = -1;
        while (i < tLen - 1)
        {
            if (j == -1 || needle[i] == needle[j])
            {
                ++i;
                ++j;
                next[i] = j;
            }
            else
            {
                j = next[j];
            }
        }
        return next;
    }
};
// 7 ms

 

[LeetCode] Implement strStr()

标签:else   log   size   www   art   example   ret   www.   amp   

原文地址:https://www.cnblogs.com/immjc/p/8543882.html

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