Implement strStr()
Description:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Code1:
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]; }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; }
Code2:
int strStr(string a, string b) {//a为目标串,b为字串 if (b == "") return 0; if (b.size() > a.size() ) return -1; for (int i = 0; i <= a.size()-b.size(); ++i) { int j = 0; for (; j < b.size(); ++j) { if (a[i+j]!=b[j]) break; } if (j==b.size()) return i; } return -1; }