Code Lab

Modo entrevista. Cronômetro de 15 min, sem dicas e sem autocompletar

Reverse the word order, keep the spaces

DifícilStrings15 min

Write a function reverseWordOrder(sentence) that returns a new string with the words in reverse order. The spaces between the words stay where they are: 'This is sample text' becomes 'text sample is This'.

  • A word is a run of characters that are not spaces. Punctuation is part of the word.
  • Words are separated only by spaces (no tabs, no line breaks). A gap can be one space or more.
  • Every gap of whitespace keeps its length and its place, also at the start and at the end of the string. Only the words move: ' Hello world ' becomes ' world Hello '.
  • The words themselves are not reversed.
  • A string without words (empty or only spaces) is returned unchanged.

If you split on one space and join back with one space, the gaps move together with the words. A loop or a regular expression that finds the words and the gaps works better.

Exemplos

reverseWordOrder('This is sample text')

Retorna 'text sample is This'

reverseWordOrder('  Hello   world ')

Retorna ' world Hello '

reverseWordOrder('a  b c')

Retorna 'c b a'

Cobrada em Amazon · Fonte

Carregando o editor...
  1. EntradareverseWordOrder('This is sample text')
    Esperado'text sample is This'
  2. EntradareverseWordOrder(' Hello world ')
    Esperado' world Hello '
  3. EntradareverseWordOrder('Hello')
    Esperado'Hello'

Os testes ocultos rodam no envio