Skip to content

Commit b1ff66c

Browse files
committed
leetcode 1/20/2014
1 parent b4a4118 commit b1ff66c

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

‎LeetCode/strStr.cpp‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include <iostream>
2+
#include <string>
3+
#include <cstring>
4+
#include <vector>
5+
using namespace std;
6+
7+
#define REP(i,n) for(int i=0;i<(n);++i)
8+
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
9+
10+
class Solution {
11+
public:
12+
char *strStr(char *haystack, char *needle) {
13+
int n = strlen(haystack);
14+
int m = strlen(needle);
15+
16+
if (m == 0) return haystack;
17+
18+
vector<int> pi(m, -1);
19+
int k = -1;
20+
FOR(q,1,m-1) {
21+
while (k >= 0 && needle[k + 1] != needle[q]) k = pi[k];
22+
if (needle[k + 1] == needle[q]) ++k;
23+
pi[q] = k;
24+
}
25+
26+
k = -1;
27+
REP(i,n) {
28+
while (k >= 0 && needle[k + 1] != haystack[i]) k = pi[k];
29+
if (needle[k + 1] == haystack[i]) ++k;
30+
if (k == m - 1) return haystack + i - m + 1;
31+
}
32+
33+
return NULL;
34+
}
35+
};
36+
37+
int main() {
38+
char pattern[] = "afds";
39+
char text[] = "";
40+
Solution s = Solution();
41+
char *ret = s.strStr(text, pattern);
42+
if (ret == NULL) cout << "NULL" << endl;
43+
else {
44+
int m = strlen(pattern);
45+
REP(i,m) cout << ret[i];
46+
cout << endl;
47+
}
48+
return 0;
49+
}

0 commit comments

Comments
 (0)