File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments