4/05/2014

Leetcode -- Implement strStr()

 class Solution {  
 public:  
   char *strStr(char *haystack, char *needle) {  
     char * p = haystack;  
     char * q = needle;  
     int h = 0;  
     while(*p) {  
       p++;  
       h++;  
     }  
     int n = 0;  
     while(*q) {  
       q++;  
       n++;  
     }      
     p = haystack;  
     q = needle;  
     if(!*q) {  
       return p;  
     }  
     while(*p && h >= n) {  
       q = needle;  
       if(*q == *p) {  
         char * r = p;  
         while(*r && *q && *r==*q) {  
           r++;  
           q++;  
         }  
         if(!*q) {  
           return p;  
         }  
       }  
       p++;  
       h--;  
     }  
     return NULL;  
   }  
 };  

No comments: