-
Notifications
You must be signed in to change notification settings - Fork 0
/
Implement strStr().cpp
36 lines (32 loc) · 953 Bytes
/
Implement strStr().cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// https://oj.leetcode.com/problems/implement-strstr/
class Solution {
public:
char *strStr(char *haystack, char *needle) {
if (haystack == nullptr || needle == nullptr) {
return nullptr;
}
if (!*needle) {
return haystack;
}
char *needle_begin = needle;
char *first_match = "";
while (*haystack && *needle) {
if (*haystack == *needle) {
if (!*first_match) {
first_match = haystack;
}
haystack++;
needle++;
} else {
needle = needle_begin;
if (*first_match) {
haystack = first_match + 1;
first_match = "";
} else {
haystack++;
}
}
}
return *needle ? nullptr : first_match;
}
};