File tree Expand file tree Collapse file tree 1 file changed +13
-7
lines changed Expand file tree Collapse file tree 1 file changed +13
-7
lines changed Original file line number Diff line number Diff line change 1
1
namespace Algorithms.Strings
2
2
3
3
module KnuthMorrisPratt =
4
- let getFailureArray ( pattern : string ): list < int > =
4
+ let getFailureArray ( pattern : string ) : list < int > =
5
5
let mutable failure = [ 0 ]
6
6
let mutable i = 0
7
7
let mutable j = 1
8
8
9
9
while j < pattern.Length do
10
10
if pattern.[ i] = pattern.[ j] then
11
11
i <- i + 1
12
+ j <- j + 1
13
+ failure <- failure @ [ i ]
14
+
12
15
elif i > 0 then
13
16
i <- failure.[ i - 1 ]
14
-
15
- j <- j + 1
16
- failure <- failure |> List.append [ i ]
17
+ else
18
+ j <- j + 1
19
+ failure <- failure @ [ i ]
17
20
18
21
failure
19
22
@@ -24,7 +27,7 @@ module KnuthMorrisPratt =
24
27
/// <param name="pattern"></param>
25
28
/// <param name="text"></param>
26
29
/// <returns></returns>
27
- let kmp ( pattern : string , text : string ): bool =
30
+ let kmp ( pattern : string , text : string ) : bool =
28
31
// 1) Construct the failure array
29
32
let failure = getFailureArray pattern
30
33
@@ -36,15 +39,18 @@ module KnuthMorrisPratt =
36
39
while i < text.Length do
37
40
if pattern.[ j] = text.[ i] then
38
41
if j = pattern.Length - 1 && ( not result) then
42
+ i <- text.Length
39
43
result <- true
40
44
41
45
j <- j + 1
46
+ i <- i + 1
42
47
43
48
// If this is a prefix in our pattern
44
49
// just go back far enough to continue
45
50
elif j > 0 && ( not result) then
46
51
j <- failure.[ j - 1 ]
47
52
48
- i <- i + 1
53
+ else
54
+ i <- i + 1
49
55
50
- result
56
+ result
You can’t perform that action at this time.
0 commit comments