28. Implement strStr()(重要!)

来源:互联网 发布:深入理解linux内核4.4 编辑:程序博客网 时间:2024/05/22 09:32

Implement strStr().

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

注意needle为“”返回的是0.

一定要熟悉KMP算法!

class Solution {public:int strStr(string haystack, string needle) {int lenn = needle.size();int lenh = haystack.size();if (lenn == 0){return 0;}if (lenn > lenh){return -1;}vector<int> next(lenn);makeNext(needle, next);int k = 0;for (int i = 0; i < lenh; i++){//i=0while (k>0 && haystack[i] != needle[k]){k = next[k - 1];}if (haystack[i] == needle[k]){k++;}if (k == lenn){return i - k + 1;}}return -1;}private:void makeNext(string needle, vector<int>&next){int len = needle.size();next[0] = 0;int k = 0;//for (int i = 1; i < len; i++){//i=1;while (k>0&&needle[i] != needle[k]){k = next[k - 1];}if (needle[i] == needle[k]){k++;//}next[i] = k;}}};


0 0
原创粉丝点击