-
Notifications
You must be signed in to change notification settings - Fork 0
/
191118-1.cpp
38 lines (36 loc) · 883 Bytes
/
191118-1.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
37
38
// https://leetcode-cn.com/problems/implement-strstr/
#include <cstdio>
#include <string>
using namespace std;
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty()) return 0;
int n = haystack.size();
int m = needle.size();
for (int i = 0; i <= n - m; ++i) {
bool mismatch = false;
for (int j = 0; j < m; ++j) {
if (haystack[i + j] != needle[j]) {
mismatch = true;
break;
}
}
if (!mismatch) {
return i;
}
}
return -1;
}
};
int main()
{
Solution s;
printf("%d\n", s.strStr("hello", "ll")); // answer: 2
printf("%d\n", s.strStr("aaaaa", "bba")); // answer: -1
printf("%d\n", s.strStr("hello", "")); // answer: 0
printf("%d\n", s.strStr("", "")); // answer: 0
printf("%d\n", s.strStr("a", "a")); // answer: 0
printf("%d\n", s.strStr("mississippi", "mississippi")); // answer: 0
return 0;
}