Reverse Words in a String III — LeetCode 557 Python Solution
EasyTwo PointersString
- Problem
- #557
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example
- Input
- s = "Let's take LeetCode contest"
- Output
- "s'teL ekat edoCteeL tsetnoc"
Python solution
Python
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(t[::-1] for t in s.split())Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 557. Reverse Words in a String III is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 557. Reverse Words in a String III?
- LeetCode 557. Reverse Words in a String III is rated Easy on LeetCode.
- What is the time complexity of LeetCode 557. Reverse Words in a String III?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 557. Reverse Words in a String III?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 557. Reverse Words in a String III cover?
- LeetCode 557. Reverse Words in a String III is tagged Two Pointers and String on LeetCode.