Skip to content

Commit 94e5ade

Browse files
committed
add 028 cpp version(4ms)
1 parent b19f59f commit 94e5ade

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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+
};

0 commit comments

Comments
 (0)