Leetcode Implement strStr()

OpenSoucre發表於2014-06-23

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;
        }
    }
};

 

相關文章