Skip to content

Commit 49b5b67

Browse files
committed
Time: 0 ms (100.00%), Space: 6.4 MB (11.56%) - LeetHub
1 parent 7df865f commit 49b5b67

File tree

1 file changed

+25
-41
lines changed

1 file changed

+25
-41
lines changed
Lines changed: 25 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,42 @@
11
class Solution {
22
public:
3-
4-
vector<int> prefix_function(string s)
5-
{
6-
int n = s.size();
7-
vector<int> pi(n,0);
3+
int strStr(string haystack, string needle) {
4+
5+
int n = needle.size();
6+
vector<int> lps(n,0);
87

9-
for(int i = 1; i<n; i++)
8+
for(int i = 1; i < n; ++i)
109
{
11-
int j = pi[i-1];
12-
while(j>0 and s[i]!=s[j])
13-
j = pi[j-1];
14-
15-
if(s[i] == s[j])
16-
j++;
17-
pi[i] = j;
10+
int j = lps[i-1] ;
11+
12+
while(j > 0 and needle[i] != needle[j])
13+
j = lps[j-1];
14+
15+
if(needle[i] == needle[j])
16+
++j;
17+
18+
lps[i] = j;
1819
}
19-
//Time Complexity = O(n)
20-
return pi;
21-
}
22-
23-
int strStr(string haystack, string needle)
24-
{
25-
if(needle.length() == 0)
26-
return 0;
2720

28-
vector<int> prefix = prefix_function(needle);
2921

30-
int pos = -1;
31-
int i(0), j(0);
32-
while(i<haystack.size())
22+
int i = 0, j = 0, m = haystack.length();
23+
24+
while(i < m)
3325
{
3426
if(haystack[i] == needle[j])
3527
{
36-
i++;
37-
j++;
28+
++i,++j;
3829
}
39-
else
40-
{
41-
if(j!=0)
42-
j = prefix[j-1];
30+
else if(haystack[i] != needle[j]){
31+
if(j == 0)
32+
++i;
4333
else
44-
i++;
45-
}
46-
47-
if(j == needle.size())
48-
{
49-
pos = i - needle.size();
50-
break;
34+
j = lps[j-1];
5135
}
36+
if(j == n)
37+
return i - n;
5238
}
53-
54-
cout<<pos;
55-
return pos;
5639

40+
return -1;
5741
}
5842
};

0 commit comments

Comments
 (0)