-
Notifications
You must be signed in to change notification settings - Fork 0
/
strStr.cpp
102 lines (79 loc) · 2.32 KB
/
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include<string>
#include<iostream>
/*
https://leetcode.com/problems/implement-strstr/
*/
namespace strStr {
int strStr(const std::string& haystack, const std::string& needle) {
//The case that needle is empty.
if (needle.length() == 0)
return 0;
//The case that haystack is empty.
if (haystack.empty())
return -1;
auto ch1 = haystack.begin();
auto ch2 = needle.begin();
int res = -1;
bool in_sequence = false;
for (int i = 0; i < haystack.length(); i++)
{
if (not in_sequence && *ch1 == *ch2) {
++ch1;
++ch2;
res = i;
in_sequence = true;
if (ch2 == needle.end())
return res;
}
else if (in_sequence && *ch1 != *ch2) {
ch2 = needle.begin();
ch1 = haystack.begin() + res + 1;
i = res;
res = -1;
in_sequence = false;
}
else if (in_sequence and *ch1 == *ch2) {
++ch1;
++ch2;
if (ch2 == needle.end())
return res;
}
else if (not in_sequence && *ch1 != *ch2) {
++ch1;;
}
}
return -1;
}
//Check all the test-cases.
bool strStr_Test() {
//Test-case 1:
if (strStr("lello", "ll") != 2)
return false;
//Test-case 2:
if (strStr("lelo", "ll") != -1)
return false;
//Test-case 3:
if (strStr("leol", "ll") != -1)
return false;
//Test-case 4:
if (strStr("aaaaa", "bba") != -1)
return false;
//Test-case 5:
if (strStr("", "") != 0)
return false;
//Test-case 6:
if (strStr("abcd", "") != 0)
return false;
//Test-case 7:
if (strStr("", "abcd") != -1)
return false;
//Test-case 8:
if (strStr("mississippi", "issip") != 4)
return false;
//Test-case 9:
if (strStr("mississippi", "si") != 3)
return false;
std::cout << "All test-cases for strStr method passed." << std::endl;
return true;
}
}