Skip to content

Commit a1936ff

Browse files
committed
28. More understandable solution for me.
1 parent d361476 commit a1936ff

File tree

2 files changed

+63
-25
lines changed

2 files changed

+63
-25
lines changed

kmp.py

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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')

main.cpp

+24-25
Original file line numberDiff line numberDiff line change
@@ -16,40 +16,39 @@ class Solution {
1616
return 0;
1717
}
1818

19-
auto t = vector<int>(needle.length());
19+
auto p = vector<int>(needle.length());
2020

21-
int pos = 1;
22-
int cnd = 0;
21+
int i = 1;
22+
int j = 0;
2323

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++;
2829
} 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];
3235
}
3336
}
34-
35-
pos++;
36-
cnd++;
3737
}
3838

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;
4746
}
4847
} 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++;
5352
}
5453
}
5554
}

0 commit comments

Comments
 (0)