Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
[Solution]
class Solution {
public:
char *strStr(char *haystack, char *needle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
char *p = haystack;
char *q = needle;
int len = strlen(needle);
// q is null
if(len <= 0){
return p;
}
// q is not null
int i = 0;
while(*p != '\0'){
if(*p != *q){
p = p-i+1;
i = 0;
q = needle;
}
else{
q++;
p++;
i++;
if(*q == '\0'){
break;
}
}
}
if(*q == '\0'){
return p-len;
}
else{
return NULL;
}
}
};
说明:版权所有,转载请注明出处。 Coder007的博客