Show problems as
Classic problem #557EasyTwo PointersString

Reverse Words in a String III

Real-world version: Flip Each Word on the Banner
Tracked in this browser only
Read Reverse Words in a String III on LeetCode(opens in a new tab)

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

A sign shop is setting a banner from the text line. The text holds one or more words written left to right, each pair of neighbouring words separated by exactly one space, with no space before the first word or after the last. A word is a run of characters that contains no space, and its characters may be letters, digits or punctuation.

The shop wants a mirrored banner: every word keeps its place in the line, but the characters inside each word are set in the opposite order.

Return the text of the mirrored banner, with the words still separated by a single space.

Examples

Example 1

Input
line = "stamp the wide banner"
Output
"pmats eht ediw rennab"

Each of the four words is set backwards, and the four words stay in the order they were given, still one space apart.

Example 2

Input
line = "lot-42 c3po hi!"
Output
"24-tol op3c !ih"

Digits and punctuation are characters of their word like any other, so they move with the rest of the word.

Example 3

Input
line = "mirror rotor level"
Output
"rorrim rotor level"

Two of these words read the same backwards, so only the first word changes.

Constraints

  • 1 <= line.length <= 5 * 10^4
  • line holds printable ASCII characters.
  • line has no leading or trailing space, and words are separated by exactly one space.

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 flip_each_word(line: str) -> str:
Java
public String flipEachWord(String line)