28. Implement strStr()

1,题目要求
Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
这里写图片描述
在字符串A中返回第一个出现字符串B的索引,如果B不是A的一部分,则返回-1。

2,题目思路
个人的想法是按照substr方法,来依次比较。这样虽然也比较暴力,但是比直接的按字符比较要快很多,最后时间也是7ms,不算最快,但也是可取的。
还有的KMP算法,专门用于这类的字符串的比较,算法比较复杂,日后再做讨论。

3,程序源码

class Solution {
public:
    int strStr(string haystack, string needle) {
        auto len = needle.size();
        if(len == 0)    return 0;
        if(haystack.size() < len)  return -1;
        for(int i=0;i<=haystack.size()-len;i++){
            if(haystack.substr(i, len) == needle)   return i;
        }
        return -1;
    }
};

KMP算法的解法:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int m = haystack.length(), n = needle.length();
        if (!n) return 0;
        vector<int> lps = kmpProcess(needle);
        for (int i = 0, j = 0; i < m; ) {
            if (haystack[i] == needle[j]) { 
                i++;
                j++;
            }
            if (j == n) return i - j;
            if (i < m && haystack[i] != needle[j]) {
                if (j) j = lps[j - 1];
                else i++;
            }
        }
        return -1;
    }
private:
    vector<int> kmpProcess(string& needle) {
        int n = needle.length();
        vector<int> lps(n, 0);
        for (int i = 1, len = 0; i < n; ) {
            if (needle[i] == needle[len])
                lps[i++] = ++len;
            else if (len) len = lps[len - 1];
            else lps[i++] = 0;
        }
        return lps;
    }
};

猜你喜欢

转载自blog.csdn.net/lym940928/article/details/80722973