Skip to content

Commit ace9119

Browse files
Fix kmp algorithm (#19)
1 parent 7c56e7f commit ace9119

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed
Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,22 @@
11
namespace Algorithms.Strings
22

33
module KnuthMorrisPratt =
4-
let getFailureArray (pattern: string): list<int> =
4+
let getFailureArray (pattern: string) : list<int> =
55
let mutable failure = [ 0 ]
66
let mutable i = 0
77
let mutable j = 1
88

99
while j < pattern.Length do
1010
if pattern.[i] = pattern.[j] then
1111
i <- i + 1
12+
j <- j + 1
13+
failure <- failure @ [ i ]
14+
1215
elif i > 0 then
1316
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 ]
1720

1821
failure
1922

@@ -24,7 +27,7 @@ module KnuthMorrisPratt =
2427
/// <param name="pattern"></param>
2528
/// <param name="text"></param>
2629
/// <returns></returns>
27-
let kmp (pattern: string, text: string): bool =
30+
let kmp (pattern: string, text: string) : bool =
2831
// 1) Construct the failure array
2932
let failure = getFailureArray pattern
3033

@@ -36,15 +39,18 @@ module KnuthMorrisPratt =
3639
while i < text.Length do
3740
if pattern.[j] = text.[i] then
3841
if j = pattern.Length - 1 && (not result) then
42+
i <- text.Length
3943
result <- true
4044

4145
j <- j + 1
46+
i <- i + 1
4247

4348
// If this is a prefix in our pattern
4449
// just go back far enough to continue
4550
elif j > 0 && (not result) then
4651
j <- failure.[j - 1]
4752

48-
i <- i + 1
53+
else
54+
i <- i + 1
4955

50-
result
56+
result

0 commit comments

Comments
 (0)