Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: s = "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Example 2:
Input: s = "Mr Ding" Output: "rM gniD"
Constraints:
1 <= s.length <= 5 * 104s contains printable ASCII characters.s does not contain any leading or trailing spaces.s.s are separated by a single space.This approach involves splitting the given string into words, reversing each word individually, and then joining them back together.
This C solution involves iterating over the string and reversing each word individually. We keep track of the start of each word and reverse the word in place when we encounter a space.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), as only a constant amount of extra space is used.
This involves using a two-pointer technique to reverse the characters within each word in place, thus preserving the overall space complexity.
In this C solution, a two-pointer technique is applied to reverse individual words within the string in place, using a helper function.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Split and Reverse Each Word | Time Complexity: O(n), where n is the length of the string. |
| Two Pointers Inline Reversal | Time Complexity: O(n) |
Reverse Words in a String iii | LeetCode 557 | C++ • Knowledge Center • 27,654 views views
Watch 9 more video solutions →Practice Reverse Words in a String III with our built-in code editor and test cases.
Practice on FleetCode