Skip to content

Commit afa2283

Browse files
Add files via upload
1 parent 5f744aa commit afa2283

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// 这道题目完全在考察KMP算法
2+
// Runtime: 4 ms, faster than 91.22% of C++ online submissions for Implement strStr().
3+
// Memory Usage: 9.3 MB, less than 21.43% of C++ online submissions for Implement strStr().
4+
5+
class Solution
6+
{
7+
public:
8+
int strStr(string s, string p)
9+
{
10+
// 边界条件处理
11+
if (p.length() == 0) return 0;
12+
if (s.length() == 0 && p.length() != 0) return -1;
13+
14+
// 获取next数组
15+
vector<int> next(p.length());
16+
getNext(next, p);
17+
18+
// KMP
19+
int i = 0, j = 0;
20+
while (i < s.length() && j < static_cast<int>(p.size())
21+
{
22+
if (j == -1 || s[i] == p[j])
23+
++i, ++j;
24+
else
25+
j = next[j];
26+
}
27+
return j == p.length() ? i - j : -1;
28+
}
29+
private:
30+
void getNext(vector<int>& next, const string& p)
31+
{
32+
next[0] = -1;
33+
int i = 0, j = -1;
34+
35+
while (i < p.length() - 1)
36+
{
37+
if (j == -1 || p[i] == p[j])
38+
{
39+
++i, ++j;
40+
next[i] = j;
41+
}
42+
else
43+
j = next[j];
44+
}
45+
}
46+
};

0 commit comments

Comments
 (0)