Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 820. Short Encoding of Words in F#

Shohei Yoshida's photo
Shohei Yoshida
·Jun 20, 2022·

1 min read

URL

leetcode.com/problems/short-encoding-of-words

Code

github.com/syohex/dotnet-study/blob/master/..

open System

let minimumLengthEncoding (words: string list) : int =
    let rec substrs (cs: char list) acc =
        match cs with
        | [] -> acc
        | _ :: t ->
            let str = cs |> String.Concat
            substrs t (str :: acc)

    let rec removeSubstrs (words: string list) s =
        match words with
        | [] -> s
        | h :: t ->
            let strs = substrs (h |> Seq.toList |> List.tail) []

            let s' =
                strs
                |> List.fold (fun acc s -> Set.remove s acc) s

            removeSubstrs t s'

    let s = words |> Set.ofList
    let s' = removeSubstrs words s
    s' |> Set.fold (fun acc s -> acc + s.Length + 1) 0
 
Share this