Interview Question : Trim multiple consecutive spaces from a string

前端 未结 11 824
情书的邮戳
情书的邮戳 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:53

    Keep two indices: The next available spot to put a letter in (say, i), and the current index you're examining (say, j).

    Just loop over all the characters with j, and whenever you see a letter, copy it to index i, then increment i. If you see a space that was not preceded by a space, also copy the space.

    I think this would work in-place...

提交回复
热议问题