Reverse Odd-Position Words
Problem statement
Given a string text, reverse the characters of each word at an odd one-based position and return the resulting string. Leave words at even positions unchanged.
For this exercise, assume a word is a maximal consecutive sequence of English letters, and only the literal space character separates words. Count words from left to right starting at position 1; spaces do not count as words.
For this exercise, assume every space must remain in its original position, including leading, trailing, and repeated spaces. Preserve letter case. An empty string or a string containing only spaces is returned unchanged.
For example, hello world again becomes olleh world niaga: the first and third words are reversed, while the second word stays unchanged.
Function
reverseOddPositionWords(text: String) → StringExamples
Example 1
text = "hello world again"return = "olleh world niaga"The first and third words occupy odd one-based positions.
Example 2
text = " AbC de FG "return = " CbA de GF "Spaces are preserved exactly, and spaces do not change the word counter. The first and third words are reversed with case preserved.
Example 3
text = ""return = ""There are no words to reverse.
Constraints
- For this exercise, assume
0 <= text.length <= 20000. - For this exercise, assume
textcontains only uppercase and lowercase English letters and literal spaces.