Implement strStr() [LeetCode]

时间:2022-09-23 17:53:28

Implement strStr().

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

Summary: be careful about the corner case, haystack = "", needle = ""

     char *strStr(char *haystack, char *needle) {
if(haystack[] == '\0' && needle[] == '\0')
return haystack; int hay_idx = ;
while(haystack[hay_idx] != '\0'){
bool find = true;
int tmp_idx = hay_idx;
int needle_idx = ;
while(needle[needle_idx] != '\0'){
if(haystack[tmp_idx] == '\0')
return NULL;
if(haystack[tmp_idx] != needle[needle_idx]){
find = false;
break;
}
tmp_idx ++;
needle_idx ++;
}
if(find)
return haystack + hay_idx;
else
hay_idx ++; }
return NULL;
}