题目:
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
class Solution {
public:
char *strStr(char *haystack, char *needle) {
if (!*needle) return haystack;
char *p1 = haystack, *p2 = needle;
char *p3 = haystack;
while (*++p2)
p3++;
while (*p3) {
char *beg = p1;
p2 = needle;
while (*p1 && *p2 && *p1 == *p2) {
p1++;
p2++;
}
if (!*p2)
return beg;
p1 = beg + 1;
p3++;
}
return NULL;
}
};
本文介绍了一个 C++ 实现的 strStr() 函数,该函数用于在一个字符串 (haystack) 中查找另一个字符串 (needle) 的首次出现位置,并返回 needle 的起始指针。如果 needle 不是 haystack 的子串,则返回 null。通过遍历和逐字符比较的方法实现了这一功能。
624

被折叠的 条评论
为什么被折叠?



