Reverse Words in a String III - Problem
Word Reversal Challenge: Given a string
Think of it as flipping each word like a pancake - the word order stays the same, but each word gets flipped individually. For example,
Goal: Transform each word by reversing its character order
Input: A string with words separated by single spaces
Output: The same string with each word's characters reversed
s containing multiple words separated by spaces, your task is to reverse the characters within each individual word while keeping the words in their original positions and preserving all whitespace.Think of it as flipping each word like a pancake - the word order stays the same, but each word gets flipped individually. For example,
"Hello World" becomes "olleH dlroW".Goal: Transform each word by reversing its character order
Input: A string with words separated by single spaces
Output: The same string with each word's characters reversed
Input & Output
example_1.py — Basic word reversal
$
Input:
s = "Let's take LeetCode contest"
›
Output:
"s'teL ekat edoCteeL tsetnoc"
💡 Note:
Each word is reversed individually: 'Let's' becomes 's'teL', 'take' becomes 'ekat', 'LeetCode' becomes 'edoCteeL', and 'contest' becomes 'tsetnoc'. The spaces between words are preserved.
example_2.py — Single word
$
Input:
s = "God"
›
Output:
"doG"
💡 Note:
With only one word, we simply reverse its characters: 'G' and 'd' swap positions while 'o' stays in the middle, resulting in 'doG'.
example_3.py — Mixed length words
$
Input:
s = "I love programming"
›
Output:
"I evol gnimmargor"
💡 Note:
Single character 'I' remains unchanged, 'love' becomes 'evol', and 'programming' becomes 'gnimmargor'. Each word boundary is preserved by the spaces.
Constraints
- 1 ≤ s.length ≤ 5 × 104
- s contains printable ASCII characters
- s does not contain any leading or trailing spaces
- There is at least one word in s
- All the words in s are separated by a single space
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code