Thursday, January 23, 2014

[leetcode] Implement strStr()


Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
Algorithm:
This problem is easy but also tricky.
1. need 2 pointers for the haystack and needle each.
2. pay attention when needle is empty, should return haystack directly.
3. the pointer for haystack should traverse all the words in haystack.
Pay attention: for char* initialization: char a[] = "the words in a";
My code:
 char *strStr(char *haystack, char *needle) {
        int m = strlen(haystack);
        int n = strlen(needle);
        if(n == 0) return haystack;
        if(m < n) return NULL;
        int i = 0;
        int j = 0;
        while(i < m){
            if(haystack[i] == needle[j]){
                i++;
                j++;
            } else{
                i = i-j+1;
                j = 0;
                continue;
            }
            if(j == n){
                return &haystack[i-n];
            }
        }
        if (i == m)
            return NULL;
    }

No comments:

Post a Comment