-
-
Notifications
You must be signed in to change notification settings - Fork 447
/
knuth_morris_prat.dart
101 lines (87 loc) · 2.27 KB
/
knuth_morris_prat.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import 'package:test/test.dart';
/// Preprocess pattern to identify any suffixes that are identical to prefixes
/// in the given string.
///
/// Build a pattern which tells us where to continue iteration from if we
/// get a mismatch between the character
///
/// Step through the text one character at a time and compare it to a character in
/// the pattern updating our location within the pattern if necessary
bool stringCompare(String string, String subString) {
if (subString.isEmpty) {
return false;
}
List<int> pattern =
new List<int>.generate(subString.length, (int index) => -1);
int i = 1;
int j = 0;
while (i < subString.length) {
if (subString[i] == subString[j]) {
pattern[i] = j;
i++;
j++;
} else if (j > 0) {
j = pattern[j - 1] + 1;
} else {
i++;
}
}
return stringCompareHelper(string, subString, pattern);
}
bool stringCompareHelper(String string, String subString, List<int> pattern) {
int i = 0;
int j = 0;
while (i + subString.length - j <= string.length) {
if (string[i] == subString[j]) {
if (j == subString.length - 1) {
return true;
}
i++;
j++;
} else if (j > 0) {
j = pattern[j - 1] + 1;
} else {
i++;
}
}
return false;
}
void main() {
String string;
String subString;
test(('KMP: '), () {
string = 'aefoaefcdaefcdaed';
subString = 'aefcdaed';
expect(stringCompare(string, subString), isTrue);
});
test(('KMP: '), () {
string = 'testwafwafawfawfawfawfawfawfawfa';
subString = 'fawfawfawfawfa';
expect(stringCompare(string, subString), isTrue);
});
test(('KMP: '), () {
string = 'aabc';
subString = 'abc';
expect(stringCompare(string, subString), isTrue);
});
test(('KMP: '), () {
string = 'adafccfefbbbfeeccbcfd';
subString = 'ecb';
expect(stringCompare(string, subString), isFalse);
});
test(('KMP: '), () {
string = 'akash';
subString = 'christy';
expect(stringCompare(string, subString), isFalse);
});
test(('KMP: '), () {
string = '';
subString = 'asd';
expect(stringCompare(string, subString), isFalse);
});
test(('KMP: '), () {
string = 'asd';
subString = '';
expect(stringCompare(string, subString), isFalse);
});
}