Implement strStr()

来源:互联网 发布:淘宝企业账号怎么注册 编辑:程序博客网 时间:2024/06/05 14:37

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

思路就是暴力搜,char* tmp = &haystack[i]; tmp++;  这步比较关键,指针还是很重要的!

class Solution {public:    char *strStr(char *haystack, char *needle) {     if (haystack == NULL || needle == NULL) {             return NULL;         }                  int hlen = strlen(haystack);         int nlen = strlen(needle);         if (hlen < nlen) {             return NULL;         }                  int j;                  for (int i = 0; i < hlen-nlen + 1; i++) {             char* tmp = &haystack[i];             for (j = 0; j < nlen; j++) {                if (*tmp != needle[j]) {                         break;                 }                 tmp++;             }                         if (j == nlen) {                 return &haystack[i];             }         }    }};



0 0
原创粉丝点击