forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KMP.dart
73 lines (67 loc) · 1.75 KB
/
KMP.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*The KMP matching algorithm uses degenerating property (pattern having same sub-patterns appearing more than once in the pattern)
of the pattern and improves the worst case complexity to O(n). The basic idea behind KMP’s algorithm is: whenever we detect a mismatch
(after some matches), we already know some of the characters in the text of the next window. This information is used to avoid
matching the characters that will anyway match.*/
import 'dart:io';
List prefix_function (String pattern)
{
var m = pattern.length;
var pi = [];
pi.add(-1);
var k = -1;
for (var j = 1; j < m; j++)
{
while (k > -1 && pattern[k + 1] != pattern[j])
{
k = pi[k];
}
if (pattern[k + 1] == pattern[j])
{
k = k + 1;
}
pi.insert(j,k);
}
return pi;
}
void KMP_matcher (String text, String pattern)
{
var n = text.length;
var m = pattern.length;
var pi = [];
pi = prefix_function(pattern);
var j = -1; //number of chars matched
for (var i = 0; i < n; i++)
{
while (j >= 0 && pattern[j+1] != text[i])
{
j = pi[j]; //next char doesnot match
}
if (pattern[j+1] == text[i])
{
j = j + 1;
}
if (j == m - 1)
{
var result = i - m + 2;
print ("Pattern found at position: $result");
j = pi[j];
}
}
}
main()
{
print ("Enter Text:");
String text = stdin.readLineSync();
print ("Enter Pattern:");
String pattern = stdin.readLineSync();
KMP_matcher (text, pattern);
return 0;
}
/*
Enter Text:
gfmghdmgmgcc
Enter Pattern:
mg
Pattern found at position: 3
Pattern found at position: 7
Pattern found at position: 9 */