Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 345. Reverse Vowels of a String in F#

Shohei Yoshida's photo
Shohei Yoshida
·Nov 4, 2022·

1 min read

URL

leetcode.com/problems/reverse-vowels-of-a-s..

Code

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

let reverseVowels (s: string) : string =
    let isVowel (c: char) : bool =
        let c = System.Char.ToLower(c)

        c = 'a'
        || c = 'e'
        || c = 'i'
        || c = 'o'
        || c = 'u'

    let rec nextVowel pos (cs: char []) checkFn nextStep =
        if checkFn pos then
            if isVowel cs.[pos] then
                pos
            else
                nextVowel (pos + nextStep) cs checkFn nextStep
        else
            pos

    let rec reverseVowels' left right (cs: char []) =
        if left >= right then
            cs |> System.String
        else
            let left' = nextVowel left cs (fun n -> n < cs.Length) 1
            let right' = nextVowel right cs (fun n -> n >= 0) -1

            if left' < right' then
                let tmp = cs.[left']
                cs.[left'] <- cs.[right']
                cs.[right'] <- tmp
                reverseVowels' (left' + 1) (right' - 1) cs
            else
                cs |> System.String

    reverseVowels' 0 (s.Length - 1) (s |> Seq.toArray)
 
Share this