Implement strStr()
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
The fastest Boyer-Moorer algorithm can be found here.
class Solution { public: char *strStr(char *haystack, char *needle) { // Start typing your C/C++ solution below // DO NOT write int main() function if (!haystack || !needle) return NULL; if (!*needle) return haystack; string const text(haystack); string const pattern(needle); size_t const pMax = pattern.size() - 1; for(size_t tailPos = pMax; tailPos < text.size();){ size_t tPos = tailPos; int pPos = pMax; for(; pPos >= 0; --pPos, --tPos){ if (text[tPos] != pattern[pPos]){ ++tailPos; break; } }//for pPos if (pPos < 0) return (haystack + tailPos - pMax); }//for tPos return NULL; } };
No comments:
Post a Comment