标签:
Description:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Code:
vector<int> getNext ( string&t ) { size_t n = t.length(); vector<int>next(n,-1); int i = 0, j = -1; while ( i < n-1 ) { if ( j == -1 || t[i] == t[j]) { ++i; ++j; next[i] = j; } else j = next[j]; } for (int i = 0; i < next.size(); ++i) cout << next[i]; cout << endl; return next; } int indexKMP( string& t, string&w, vector<int>& next ) { int i = 0, j = 0; int lengthT = t.length(); int lengthW = w.length(); while ( i < lengthT && j < lengthW ) { if ( j == -1 || t[i] == w[j] ) //继续比较后继字符 { ++i; ++j; } else j = next[j]; } if ( j == lengthW ) return i - lengthW; else return -1; } int strStr(string haystack, string needle) { if (needle == "") return 0; if (haystack == "") return -1; vector<int>next; next = getNext(needle); return indexKMP(haystack,needle,next); return -1; }
标签:
原文地址:http://www.cnblogs.com/happygirl-zjj/p/4774034.html