当前位置:编程学习 > C/C++ >>

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

 

 
补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,