[LeetCode] Implement strStr()

Posted immjc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] Implement strStr()相关的知识,希望对你有一定的参考价值。

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()的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode OJ 225Implement Stack using Queues

LeetCode Implement Queue using Stacks

[LeetCode]Implement Stack using Queues

LeetCode:Implement Queue using Stacks

LeetCode:Implement Stack using Queues

LeetCode Implement Stack using Queues