← DiffPush

Reverse words in string

Baseline Strings · Easy O(n) · O(n)

Rewinding the Dispatch Log

A transit control console records incident reports as free-form text lines, and operators reviewing the day want the newest framing first — the log reader reverses the order of the words in each line. The raw lines are messy: extra gaps between entries, padding at either end. The rewound line must be tidy, with exactly one space between words and no padding.

Input: A string s of words separated by one or more spaces, possibly with leading or trailing spaces.

Output: A string with the words of s in reverse order, joined by a single space, with no leading or trailing spaces.

Constraints

Examples

Example 1

Input: {"s":"the sky is blue"}
Output: "blue is sky the"
Four cleanly separated words come back in the opposite order.

Example 2

Input: {"s":"  hello world  "}
Output: "world hello"
Padding at both ends is discarded, and only one space separates the reversed words.

Solve this in your browser →

Also on LeetCode ↗