All problems
0186MediumTwo PointersString

Read the Caption Back to Front

Tracked in this browser only
Write code

Trains the technique from

LeetCode 151Reverse Words in a String

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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