Implement strStr()

来源:互联网 发布:手机淘宝退货怎么退 编辑:程序博客网 时间:2024/06/08 10:24

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) {const char* T = haystack.c_str();const char* p = needle.c_str();int n = (int)strlen(T), i = 0;//文本串指针int m = (int)strlen(p), j = 0;//模式串指针int *Next = new int[m];int t = Next[0] = -1;//模式串指针while (j<m - 1) {if (t<0 || needle[j] == needle[t]) {Next[++j] = ++t;}else{t = Next[t];}}i = 0; j = 0;while (i<n&&j<m){if (j<0 || T[i] == p[j]) {i++; j++;}else{j = Next[j];}}delete[] Next;if (j == m )return i - j;elsereturn -1;}};

0 0
原创粉丝点击