We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 2eb25bc + 0b5ba27 commit 2d4b35bCopy full SHA for 2d4b35b
String/KMP/kmp.py
@@ -0,0 +1,21 @@
1
+#!/usr/bin/env python2.7
2
+def get_kmp(xs):
3
+ res = [-1, 0]
4
+ cur = 0
5
+ for i in range(2, len(xs) + 1):
6
+ while cur >= 0 and xs[cur] != xs[i - 1]:
7
+ cur = res[cur]
8
+ cur += 1
9
+ res.append(cur)
10
+ return res
11
+
12
+def find_pattern(text, pattern):
13
+ kmp = get_kmp(pattern + ' ' + text)
14
+ return [i for i in range(len(text) - len(pattern) + 1)
15
+ if kmp[i + len(pattern) * 2 + 1] == len(pattern)]
16
17
18
+if __name__ == '__main__':
19
+ text = raw_input("Input text: ")
20
+ pattern = raw_input("Input pattern: ")
21
+ print "Pattern appears at starting indices: ", find_pattern(text, pattern)
0 commit comments