Saturday, April 13, 2013

Implement strStr() (C++)

LeetCode Implement strStr(), Feb 18 '12
 难度4,出现频率5
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

思路:下面这个是brute-force暴力解法。

int strlenp(char *str){
  int i = 0;
 while(*str++ != '\0'){
   i++;
 }

return i;
}

  char *strStr(char *haystack, char *needle) {
       if( *needle == '\0') return haystack;
       int n = strlenp(haystack) - strlenp(needle);

      for(int i=0; i <= n; i++){
           char *hay = haystack;
           char *need = needle;
           while(*hay++ == *need++) {
              if(*need == '\0') return haystack;
            }
           haystack++;
       }

       return NULL;    
    }

No comments:

Post a Comment