-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathImplement strStr()
More file actions
47 lines (47 loc) · 1.65 KB
/
Implement strStr()
File metadata and controls
47 lines (47 loc) · 1.65 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
class Solution {
public:
int strStr(string haystack, string needle) {
/****************************************************************
********************solution from website **********************
*****************************************************************/
/*int lenh = haystack.length();
int lenn = needle.length();
bool flag = true;
if(needle == "") return 0;
for(int i = 0; i < lenh - lenn + 1; i++) {
if(haystack[i] == needle[0]) {
for(int j = 0; j < lenn; j++) {
if(haystack[j + i] != needle[j]) {
flag = false;
break;
} else flag = true;
}
if(flag) return i;
}
}
return -1;
*/
/****************************************************************
********************solution from website **********************
*****************************************************************/
if(needle == "") return 0;
bool matched = true;
for(int i = 0; i< haystack.length()-needle.length()+1;i++)
{
if(haystack[i] == needle[0])//the first letter are matching
{
for(int k = 0;k<needle.length();k++)
if(needle[k] != haystack[i+k])
{
matched = false;
break;
}
else
matched = true;
if(matched == true)
return i;
}
}
return -1;
}
};