[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.

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        int len1 = strlen(haystack);
        int len2 = strlen(needle);
        if(len1<len2)
            return NULL;
        char *p = haystack;
        for(int i=0;i<=(len1-len2);i++,p++){
            if(strncmp(p,needle,len2)==0)
                return p;
        }
        return NULL;
    }//end func
};

 

posted @ 2014-08-25 11:43  Xylophone  Views(122)  Comments(0)    收藏  举报