-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementStrStr.cpp
More file actions
55 lines (51 loc) · 1.31 KB
/
Copy pathImplementStrStr.cpp
File metadata and controls
55 lines (51 loc) · 1.31 KB
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
//task 28
//1288ms 9.0mb
//manual, not used string functions
class Solution {
public:
int strStr(string haystack, string needle)
{
bool ok(false);
if (needle.length() == 0) return 0;
for (int i = 0; i< haystack.length(); i++)
{
if (needle[0] == haystack[i])
{
ok = true;
for (int j = 0; j < needle.length(); j++)
{
if (needle[j] != haystack[i+j])
{
ok = false;
break;
}
}
}
if (ok) return i;
}
return -1;
}
};
//also you can use substr()
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.size() == 0) return 0;
for(int i = 0; i < haystack.size(); i++)
if(haystack[i] == needle[0] && isEqual(haystack.substr(i), needle)) return i;
return -1;
}
bool isEqual(string s1, string s2){
if(s1.size() < s2.size()) return false;
for(int i = 0; i < s2.size(); i++)
if(s1[i] != s2[i]) return false;
return true;
}
};
//whynot ?
class Solution {
public:
int strStr(string haystack, string needle) {
return haystack.find(needle);
}
};