File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #String matching by KMP algorithm
2+
3+ def pfun (pattern ):
4+ n = len (pattern )
5+ prefix_fun = [0 ]* (n )
6+
7+ k = 0
8+ for q in range (2 , n ):
9+ while k > 0 and pattern [k + 1 ] != pattern [q ]:
10+ k = prefix_fun [k ]
11+ if pattern [k + 1 ] == pattern [q ]:
12+ k += 1
13+ prefix_fun [q ] = k
14+ return prefix_fun
15+
16+
17+ def KMP_Matcher (text , pattern ):
18+ m = len (text )
19+ n = len (pattern )
20+ flag = False
21+ text = '-' + text
22+ pattern = '-' + pattern
23+ prefix_fun = pfun (pattern )
24+ q = 0
25+
26+ for i in range (1 , m + 1 ):
27+ while q > 0 and pattern [q + 1 ] != text [i ]:
28+ q = prefix_fun [q ]
29+ if pattern [q + 1 ] == text [i ]:
30+ q += 1
31+ if q == n :
32+ print ("Pattern occurs at positions " ,i - n ) # print the index, where first match occurs.
33+ flag = True
34+ q = prefix_fun [q ]
35+ if not flag :
36+ print ('\n No match found' )
37+
38+
39+ #Output of KMP algorithm
40+ KMP_Matcher ('aabaacaadaabaaba' ,'aabaa' )
You can’t perform that action at this time.
0 commit comments