判断一个字符串是否是另一个字符串的子串(Implement strStr() )

问题描述:

这是算法中比较经典的问题,判断一个字符串是否是另一个字符串的字串。


思路:

这个题目最经典的算法应该是KMP算法,KMP算法是最优的线性算法,复杂度已经达到了这个问题的下线。但是KMP算法的过程比较复杂,在面试过程中很难在很短的时间内实现,所以在一般的面试中很少让实现KMP算法。

代码实现:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int i, j;
        for (i = j = 0; i < haystack.size() && j < needle.size();) {
            if (haystack[i] == needle[j]) {
                ++i; ++j;
            } else {
                i -= j - 1; j = 0;
            }
        }
        return j != needle.size() ? -1 : i - j;
    }
};

你可能感兴趣的:(LeetCode)