File tree 2 files changed +63
-25
lines changed
2 files changed +63
-25
lines changed Original file line number Diff line number Diff line change
1
+ haystack = 'asdabcabdjabcdabcdababcgj'
2
+ needle = 'abcdababc'
3
+
4
+ p = [0 ] * len (needle )
5
+ p [0 ] = 0
6
+
7
+ # len(needle) should be > 0 otherwise answer is 0 (like in java impl)
8
+
9
+ j , i = 0 , 1
10
+ while i < len (needle ):
11
+ if needle [j ] == needle [i ]:
12
+ p [i ] = j + 1
13
+ i += 1
14
+ j += 1
15
+ else :
16
+ if j == 0 :
17
+ p [i ] = 0
18
+ i += 1
19
+ else :
20
+ j = p [j - 1 ]
21
+
22
+ print (f'{ p = } ' )
23
+
24
+ i = j = 0
25
+ while i < len (haystack ):
26
+ if haystack [i ] == needle [j ]:
27
+ i += 1
28
+ j += 1
29
+ if j == len (needle ):
30
+ print ('Substring starts from' , i - j , haystack [i - j :i - j + len (needle )])
31
+ break
32
+ else :
33
+ if j > 0 :
34
+ j = p [j - 1 ]
35
+ else :
36
+ i += 1
37
+
38
+ if i == len (haystack ):
39
+ print ('Haystack doesnt contain needle' )
Original file line number Diff line number Diff line change @@ -16,40 +16,39 @@ class Solution {
16
16
return 0 ;
17
17
}
18
18
19
- auto t = vector<int >(needle.length ());
19
+ auto p = vector<int >(needle.length ());
20
20
21
- int pos = 1 ;
22
- int cnd = 0 ;
21
+ int i = 1 ;
22
+ int j = 0 ;
23
23
24
- t[0 ] = -1 ;
25
- while (pos < needle.length ()) {
26
- if (needle[pos] == needle[cnd]) {
27
- t[pos] = t[cnd];
24
+ p[0 ] = 0 ;
25
+ while (i < needle.length ()) {
26
+ if (needle[i] == needle[j]) {
27
+ p[i] = j + 1 ;
28
+ i++; j++;
28
29
} else {
29
- t[pos] = cnd;
30
- while (cnd >= 0 && needle[pos] != needle[cnd]) {
31
- cnd = t[cnd];
30
+ if (j == 0 ) {
31
+ p[i] = 0 ;
32
+ i++;
33
+ } else {
34
+ j = p[j - 1 ];
32
35
}
33
36
}
34
-
35
- pos++;
36
- cnd++;
37
37
}
38
38
39
- int j = 0 ;
40
- int k = 0 ;
41
- while (j < haystack.length ()) {
42
- if (needle[k] == haystack[j]) {
43
- j++;
44
- k++;
45
- if (k == needle.length ()) {
46
- return j - k;
39
+ i = 0 ;
40
+ j = 0 ;
41
+ while (i < haystack.length ()) {
42
+ if (haystack[i] == needle[j]) {
43
+ i++; j++;
44
+ if (j == needle.length ()) {
45
+ return i - j;
47
46
}
48
47
} else {
49
- k = t[k];
50
- if (k < 0 ) {
51
- j++;
52
- k ++;
48
+ if (j > 0 ) {
49
+ j = p[j - 1 ];
50
+ } else {
51
+ i ++;
53
52
}
54
53
}
55
54
}
You can’t perform that action at this time.
0 commit comments