Saturday, October 5, 2013

Implement strStr

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int len_h = strlen(haystack);
        int len_n = strlen(needle);
        if (len_h < len_n)
            return NULL;
        if (len_n == 0)
            return haystack;
        
        char *p_h = haystack, *p_n = needle;
        while (p_h <= haystack+len_h-len_n) {
            if (*p_h != *p_n) {
                p_h++;
            }
            else {
                int i;
                for (i = 0; i < len_n; i++) {
                    if (*(p_h+i) != *(p_n+i))
                        break;
                }
                if (i == len_n)
                    return p_h;
                else
                    p_h++;
            }
        }
        return NULL;
    }
};

No comments:

Post a Comment