*leetcode 28 strStr

来源:互联网 发布:com域名申请 编辑:程序博客网 时间:2024/05/19 07:07

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) {        typedef string::size_type sz;        size_t n_size = needle.size();        if (n_size == 0) return 0;        size_t h_size = haystack.size();        if (n_size > h_size) return -1;        for (int i = 0; i < h_size - n_size + 1; ++i) {            sz k = 0;            while (k != n_size && haystack[i + k] == needle[k])  ++k;            if (k == n_size) return i;                }        return -1;    }};

hehe

class Solution {public:    int strStr(string haystack, string needle) {        return haystack.find(needle);    }};

KMP 算法

http://www.cnblogs.com/c-cloud/p/3224788.html
https://discuss.leetcode.com/topic/15569/explained-4ms-easy-c-solution

class Solution {public:    int strStr(string haystack, string needle) {        typedef string::size_type sz;        sz n_size = needle.size();        if (n_size == 0) return 0;        sz h_size = haystack.size();        if (h_size < n_size) return -1;        vector <int> v(n_size, 0);        // compute the longest prefix and suffix           sz i = 1;        sz len = 0;        while (i != n_size) {             if (needle[len] == needle[i]){                ++len;                v[i] = len;                ++i;            } else {                if (len != 0)                    // 长度为len时第i+ 1 个不匹配时,尝试长度为v[len -1](长len                    // 时的最长相同前后缀);                    len = v[len - 1];                else {                    v[i] = len;                    ++i;                }            }        }         for (sz j = 0; j < n_size; ++j)            cout << v[j] << " ";        sz j = 0;        // sz can not be negative        // so if (h_size < n_size) return -1;        while (j <= h_size - n_size) {            int len = 0;            while(len != n_size && haystack[j +len] == needle[len]) ++len;            if (len == 0) ++j;            if (len == n_size) return j;            else j += len - v[len - 1];        }        return -1;    }};
原创粉丝点击