Given a string s, remove extra spaces so that words are separated by a single space, with no leading or trailing spaces.
Then reverse only the words at odd positions (0-indexed) and return the resulting string. For words [w0, w1, w2, w3, ...], the words at odd positions are w1, w3, and so on, and each of them has its characters reversed. Words at even positions stay as they are.
Function Signature
def reverse_odd_words(s: str) -> str:
Rules
-
A word is a maximal run of non-space characters. Positions count words after the extra spaces are removed, starting from 0.
-
Only the characters inside an odd-position word are reversed. The order of the words does not change.
-
If
s
contains no words, return the empty string
""
.
Constraints
-
1 <= len(s) <= 10^4
-
s
contains English letters, digits and spaces.
Examples
Input: s = "hello world foo bar"
Output: "hello dlrow foo rab"
The words are ["hello", "world", "foo", "bar"]. The words at positions 1 and 3 are world and bar, which become dlrow and rab.
Input: s = " the quick brown fox "
Output: "the kciuq brown xof"
After removing extra spaces the words are ["the", "quick", "brown", "fox"]. The words at positions 1 and 3 are quick and fox, which become kciuq and xof.
Input: s = "abc 1234 x"
Output: "abc 4321 x"
There are three words. Only 1234, at position 1, is reversed. The last word x is at position 2, so it stays the same.