[LeetCode] 28. Implement strStr()

题目链接:传送门

Description

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

Solution

题意:

寻找字符串 needle 在字符串 haystack 中第一次出现的位置,不存在输出 -1

思路:

可以直接暴力,也可以用KMP

(1) KMP

class Solution {
public:
    void getNext(vector<int>& Next, string needle) {
        int len = needle.length();
        int i = 0, j = -1;
        Next[0] = -1;
        while (i < len) {
            while (j != -1 && needle[i] != needle[j])  j = Next[j];
            Next[++i] = ++j;
        }
    }
    int strStr(string haystack, string needle) {
        if (needle == "")  return 0;
        if (haystack == "")  return -1;
        int hLen = haystack.length(), nLen = needle.length();
        vector<int> Next(nLen + 1);
        getNext(Next, needle);
        int i = 0, j = 0;
        while (i < hLen && j < nLen) {
            if (j == -1 || haystack[i] == needle[j])  ++i, ++j;
            else  j = Next[j];
        }
        if (j == nLen)  return i - j;
        return -1;
    }
};
posted @ 2018-02-20 02:42  酒晓语令  阅读(117)  评论(0编辑  收藏  举报