Interview Question : Trim multiple consecutive spaces from a string

前端 未结 11 861
情书的邮戳
情书的邮戳 2020-12-08 17:34

This is an interview question Looking for best optimal solution to trim multiple spaces from a string. This operation should be in-place operation.

input  =          


        
11条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 17:57

    Functional variant in Haskell:

    import Data.List (intercalate)
    
    trimSpaces :: String -> String
    trimSpaces =  intercalate " " . words
    

    The algorithm the next:

    1. breaks a string up into a list of words, which were delimited by white space
    2. concatenate the list inserting one space between each element in list

提交回复
热议问题