Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions Algorithms/Strings/KnuthMorrisPratt.fs
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
namespace Algorithms.Strings

module KnuthMorrisPratt =
let getFailureArray (pattern: string): list<int> =
let getFailureArray (pattern: string) : list<int> =
let mutable failure = [ 0 ]
let mutable i = 0
let mutable j = 1

while j < pattern.Length do
if pattern.[i] = pattern.[j] then
i <- i + 1
j <- j + 1
failure <- failure @ [ i ]

elif i > 0 then
i <- failure.[i - 1]

j <- j + 1
failure <- failure |> List.append [ i ]
else
j <- j + 1
failure <- failure @ [ i ]

failure

Expand All @@ -24,7 +27,7 @@ module KnuthMorrisPratt =
/// <param name="pattern"></param>
/// <param name="text"></param>
/// <returns></returns>
let kmp (pattern: string, text: string): bool =
let kmp (pattern: string, text: string) : bool =
// 1) Construct the failure array
let failure = getFailureArray pattern

Expand All @@ -36,15 +39,18 @@ module KnuthMorrisPratt =
while i < text.Length do
if pattern.[j] = text.[i] then
if j = pattern.Length - 1 && (not result) then
i <- text.Length
result <- true

j <- j + 1
i <- i + 1

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

i <- i + 1
else
i <- i + 1

result
result