[Leetcode]28. Implement strStr()

来源:互联网 发布:医院网络咨询工资高吗 编辑:程序博客网 时间:2024/05/08 22:13

Implement strStr().

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

class Solution {public:    int strStr(string haystack, string needle) {        if (needle.empty())            return 0;        const int N = haystack.size() - needle.size() + 1;        for (int i = 0; i < N; i++) {            int j = i;            int k = 0;            while (j < haystack.size() && k < needle.size() && haystack[j] == needle[k]) {                j++;                k++;            }            if (k == needle.size())                return i;        }        return -1;    }};
上面的解法是暴力解法,用KMP算法,Rabin-Karp算法等也可以。

0 0
原创粉丝点击