Saturday, October 6, 2012

F# on Algorithms - SubString


this function returns the consecutive string which has the same character. For example, the input "34445" will return "3", "444", and "5".

let str = "34445";
let getSub (str:string ref) =
    [
        let result = ref ""
        for c in (!str) do
            if !result = "" then
                result := string c
            elif (!result).EndsWith(string c) then
                result := !result + string c
            else
                yield !result
                result := string c
        yield !result]

getSub (ref str)

No comments: