haoel / leetcode

LeetCode Problems' Solutions
17.58k stars 4.91k forks source link

improvement of Implement strStr() #16

Closed ghost closed 9 years ago

ghost commented 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.

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;
    }
};
ghost commented 9 years ago

Or do you welcome such string: {'x', '\0', 'y', '\0'}

ghost commented 9 years ago

Oh, strstr in <cstring> respect NUL in a string. But I suggest giving some notices for this. It's too weird.