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
Understanding the Visualization
1
Identify the Stack
Find where each word (pancake stack) begins and ends
2
Position Spatulas
Place left spatula at bottom pancake, right spatula at top pancake
3
Flip Process
Swap pancakes at spatula positions and move spatulas toward center
4
Stack Complete
When spatulas meet, the stack is perfectly flipped - move to next plate
Key Takeaway
๐ฏ Key Insight: The two-pointer technique transforms an O(nยฒ) string manipulation problem into an elegant O(n) solution by working directly with the character array, avoiding expensive string operations and temporary objects.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code