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) {
        if(needle == NULL) return haystack;
        else{
            int len1 =strlen(haystack),len2 = strlen(needle);
            if(len2 == 0) return haystack;
            for(int i = 0 ; i < len1-len2+1; ++ i){
                if(strncmp(haystack+i,needle,len2) == 0) return haystack+i;
            }
            return NULL;
        }
    }
};

 

posted @ 2014-06-23 20:20  OpenSoucre  阅读(141)  评论(0编辑  收藏  举报