Reverse Words in a String
Real-world version: Read the Caption Back to FrontThe statement here is our own: the same inputs, outputs and technique.
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.
def read_caption_back(caption: str) -> str:public String readCaptionBack(String caption)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's