FastPrepReverse Words in a String

Reverse Words in a String

Agoda logoAgoda● MediumFULLTIMEPHONE SCREEN

Problem statement

Given a string s, return a new string that has the same words in reverse order.

A word is a run of characters that are not spaces. Letters, digits, and punctuation that touch each other belong to the same word, so "Bangkok:)" is one word.

In the returned string, words are separated by exactly one space, and there is no space at the start or the end. Any leading, trailing, or repeated spaces in s are dropped.

Function

reverseWords(s: String) → String

Examples

Example 1

s = "Hello Bangkok:)"return = "Bangkok:) Hello"

The words are "Hello" and "Bangkok:)". The :) touches Bangkok, so it stays part of that word.

Reversing the two words gives "Bangkok:) Hello".

Example 2

s = "  see you   in Bangkok  "return = "Bangkok in you see"

The words are "see", "you", "in", and "Bangkok". The two spaces at the start, the three spaces after you, and the two spaces at the end are dropped.

In reverse order, joined by single spaces, they give "Bangkok in you see".

Example 3

s = "   x-ray   "return = "x-ray"

There is only one word, "x-ray". The hyphen is not a space, so it stays inside the word.

Reversing one word changes nothing, and the spaces around it are dropped, so the answer is "x-ray".

Constraints

  • 1 <= s.length <= 10^4
  • s contains only English letters, digits, spaces, and the symbols . , ! ? : ; ( ) -
  • s contains at least one word.

More Agoda problems

See Agoda hiring insights
Saved
public String reverseWords(String s) {
    // Write your solution here.
}
Checking account…