Show problems as
Classic problem #151MediumTwo PointersString

Reverse Words in a String

Real-world version: Read the Caption Back to Front
Tracked in this browser only
Read Reverse Words in a String on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstTwo Pointers · Strings, animated step by step

A label printer emits a caption strip as the string caption. Whoever typed it was careless with the space bar, so the strip may begin with spaces, end with spaces, or hold several spaces between neighbouring words.

Treat a word as any run of characters that holds no space and cannot be extended. Hand back the caption with its words in the opposite order, joined by exactly one space each, with no space leading or trailing. Padding inside the original strip must not survive into your answer.

Letters keep their case and digits keep their value; nothing about a word itself changes, only where it sits.

Examples

Example 1

Input
caption = " gate 7 open "
Output
"open 7 gate"

The three words come back in the opposite order and the padding at both ends is dropped.

Example 2

Input
caption = "Delta"
Output
"Delta"

A single word has nothing to reorder, and its capital letter stays a capital.

Example 3

Input
caption = "load Bay 22 ready"
Output
"ready 22 Bay load"

The runs of two and three spaces each collapse to one space in the rebuilt caption.

Constraints

  • 1 <= caption.length <= 10^4
  • caption holds English letters in either case, digits, and the space character ' '
  • caption holds at least one word

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def read_caption_back(caption: str) -> str:
Java
public String readCaptionBack(String caption)