-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode_28.cpp
More file actions
59 lines (51 loc) · 1.68 KB
/
leetcode_28.cpp
File metadata and controls
59 lines (51 loc) · 1.68 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
56
57
58
59
//1.First solution : Rude solution
//@ use needle to be a seed of search index. ugly and complicate
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
if(haystack.empty() || needle.size() > haystack.size()) return -1;
int i=0;
int j=0;
bool flag = false;
int found = 0;
while(1){
if(needle[i] != haystack[j]) {
j++;
i=0;
if(flag){
j= found+1;
flag = false;
}
} else{
if(!flag){
// cout << j << endl;
found = j;
flag = true;
}
i++;
j++;
}
if(i > needle.size() -1 ) break;
if(j > haystack.size() -1) break;
//if(haystack.size() - j < needle.size()) break;
}
if(i <= needle.size() -1 ) return -1;
return j-i ;
}
//Solution 2: use haystack be a seed of search. it’s more easy and simple.
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
for(int i=0; i< haystack.size();i++){
if((i+needle.size()) > haystack.size()) return -1;
if(haystack[i] == needle[0]){
for(int j=0; j< needle.size();j++){
if(needle[j] != haystack[j+i]) break;
if(j == needle.size()-1) return i;
}
}
}
return -1;
}
};
//Solution 3:TODO KVM algorithm.