File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
solution/028.Implement strStr() Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ private:
3
+ vector<int > Next (string str)
4
+ {
5
+ vector<int > n (str.length ()) ;
6
+ n[0 ] = -1 ;
7
+ int i = 0 , pre = -1 ;
8
+ int len = str.length () ;
9
+ while (i < len)
10
+ {
11
+ while (pre >= 0 && str[i] != str[pre])
12
+ pre = n[pre] ;
13
+ ++i, ++pre ;
14
+ if (i >= len)
15
+ break ;
16
+ if (str[i] == str[pre])
17
+ n[i] = n[pre] ;
18
+ else
19
+ n[i] = pre ;
20
+ }
21
+ return n ;
22
+ }
23
+ public:
24
+ int strStr (string haystack, string needle) {
25
+ if (0 == needle.length ())
26
+ return 0 ;
27
+
28
+ vector<int > n (Next (needle)) ;
29
+
30
+ int len = haystack.length () - needle.length () + 1 ;
31
+ for (int i = 0 ; i < len; ++i)
32
+ {
33
+ int j = 0 , k = i ;
34
+ while (j < needle.length () && k < haystack.length ())
35
+ {
36
+ if (haystack[k] != needle[j])
37
+ {
38
+ if (n[j] >= 0 )
39
+ {
40
+ j = n[j] ;
41
+ continue ;
42
+ }
43
+ else
44
+ break ;
45
+ }
46
+ ++k, ++j ;
47
+ }
48
+ if (j >= needle.length ())
49
+ return k-j ;
50
+ }
51
+
52
+ return -1 ;
53
+ }
54
+ };
You can’t perform that action at this time.
0 commit comments