Skip to content

Instantly share code, notes, and snippets.

@ritalin
Created April 10, 2012 16:10
Show Gist options
  • Save ritalin/2352495 to your computer and use it in GitHub Desktop.
Save ritalin/2352495 to your computer and use it in GitHub Desktop.
Maximum Duplication String Problem for F#
//
// Maximum Duplication String Problem for F#
//
let dupstr s =
// generate suffix list
let tails (s:string) =
let rec tailsimpl (s:string) i list =
match i with
| -1 -> list
| _ -> tailsimpl s (i-1) ((s.[i].ToString()+List.head list)::list)
tailsimpl s (s.Length-1) [""]
// generate adjacent pair
let makePair xs =
Seq.zip <| List.toSeq xs <| List.toSeq (List.tail xs)
// calculate common string length
let calcLen : (seq<string * string> -> seq<int * string>) =
let commonLen s1 s2 =
Seq.zip s1 s2 |> Seq.takeWhile (fun (x,y) -> x = y) |> Seq.length
Seq.map (fun (xs, ys) -> (commonLen xs ys), xs)
// get max common string length
let maxLen : (seq<int * string> -> int * string) =
Seq.maxBy (fun (n, s) -> n)
// extract common string
let extract (n, s) =
Seq.take n s |> Seq.map (fun c -> c.ToString()) |> String.concat ""
s |> tails |> List.sort |> makePair |> calcLen |> maxLen |> extract
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment