Leetcode: Implement strStr()

2014-11-24 00:04:32 · 作者: · 浏览: 11
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
Time Limit Exceeded
char *strStr(char *haystack, char *needle) {  
        // Note: The Solution object is instantiated only once.  
        if(!*needle)return haystack;  
        while(*haystack != '\0')  
        {  
            if(*haystack == *needle)  
            {  
                char* h = haystack;  
                char* n = needle;  
                while(*h != '\0' && *n!= '\0' && *h==*n)h++,n++;  
                if(*n=='\0')  
                    return haystack;  
            }  
            haystack++;  
        }  
        return NULL;  
    }  

优化:当haystack后面的长度小于needle的长度时就不用再匹配了。
Accepted
        // Note: The Solution object is instantiated only once.  
        if(!*needle)return haystack;  
        char* pend = haystack;  
          
        char* tmp = needle;  
        while(*++tmp)pend++;  
  
        while(*pend != '\0')  
        {  
            if(*haystack == *needle)  
            {  
                char* h = haystack;  
                char* n = needle;  
                while(*h != '\0' && *n!= '\0' && *h==*n)h++,n++;  
                if(*n=='\0')  
                    return haystack;  
            }  
            haystack++;  
            pend++;  
        }  
        return NULL;  
    }