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

前端 未结 21 1959
[愿得一人]
[愿得一人] 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:03

    O(N) in space and O(N) in time solution in Python:

    def reverse_words_nosplit(str_):
      """
      >>> f = reverse_words_nosplit
      >>> f("this is a string")
      'string a is this'
      """
      iend = len(str_)
      s = ""
      while True:
        ispace = str_.rfind(" ", 0, iend)
        if ispace == -1:
          s += str_[:iend]
          break
        s += str_[ispace+1:iend]
        s += " "
        iend = ispace
      return s
    

提交回复
热议问题