Efficiently reverse the order of the words (not characters) in an array of characters

前端 未结 21 1927
[愿得一人]
[愿得一人] 2020-11-28 04:40

Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.

Example input and

21条回答
  •  长情又很酷
    2020-11-28 05:02

    pushing a string onto a stack and then popping it off - is that still O(1)? essentially, that is the same as using split()...

    Doesn't O(1) mean in-place? This task gets easy if we can just append strings and stuff, but that uses space...

    EDIT: Thomas Watnedal is right. The following algorithm is O(n) in time and O(1) in space:

    1. reverse string in-place (first iteration over string)
    2. reverse each (reversed) word in-place (another two iterations over string)
      1. find first word boundary
      2. reverse inside this word boundary
      3. repeat for next word until finished

    I guess we would need to prove that step 2 is really only O(2n)...

提交回复
热议问题