Wednesday, December 10, 2014

Implement strStr()

Q:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

T:
KMP is hard to think out. Just use two layers of loop can also work. O(m*n).

A:

class Solution {
public:
    int strStr(char *haystack, char *needle) {
        if(haystack == NULL || needle == NULL) {
            return -1;
        }
        char * h=haystack;
        char * n=needle;
        if(!*n && *h) {
            return 0;
        }
        if(!*h && *n) {
            return -1;
        }
        if(!*n && !*h) {
            return 0;
        }
        do {
            while(*h && *h != *n) {
                h++;
            }
            if(!*h) {
                return -1;
            }
            char * a=h+1;
            char * b=n+1;
            while(*a && *b && *b==*a) {
                a++;
                b++;
            }
            if(!*a && *b) {
                return -1;
            }
            if(*b) {
                h++;
            } else {
                return h-haystack;
            }
        } while (*h);
        return -1;
    }
};

No comments:

Post a Comment