Closed ghost closed 9 years ago
https://github.com/haoel/leetcode/blob/ad62b9d82e8d72a3923881840b23532216c12982/src/strStr/strStr.cpp#L60
It's confusing that char* ph does not move with the same offset as char* haystack does.
char* ph
char* haystack
This is my modified solution:
class Solution { public: char* strStr(char* haystack, char* needle) { if (!*needle) return haystack; // ["a", ""] char* ph = haystack; char* pn = needle; while (*ph && *pn) { ph++; pn++; } if (!*ph && *pn) return NULL; // ["", "a"] ph = ph - 1; while (*ph) { char* px = haystack; // start of the rest part char* py = needle; int step = 0; while (*py && *px && *px == *py) { px++; py++; if (step == 0 && *px == *needle) step = px - haystack; } if (!*py) return haystack; step = step > 0 ? step : 1; haystack += step; ph += step; } return NULL; } };
Or do you welcome such string: {'x', '\0', 'y', '\0'}
Oh, strstr in <cstring> respect NUL in a string. But I suggest giving some notices for this. It's too weird.
strstr
<cstring>
https://github.com/haoel/leetcode/blob/ad62b9d82e8d72a3923881840b23532216c12982/src/strStr/strStr.cpp#L60
It's confusing that
char* ph
does not move with the same offset aschar* haystack
does.This is my modified solution: