Reverse Words in a String III
Description
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"
Explanation: Each word is reversed individually:
"Let's" -> "s'teL"
"take" -> "ekat"
"LeetCode" -> "edoCteeL"
"contest" -> "tsetnoc"
Example 2:
Input: s = "Mr Ding"
Output: "rM gniD"
Explanation: "Mr" -> "rM", "Ding" -> "gniD"
Constraints
1 <= s.length <= 5 * 10^4s contains printable ASCII characterss does not contain any leading or trailing spacesThere is at least one word in sAll words in s are separated by a single space
Signature
...Complexity
- Time:
O(n) - Space:
O(n)
Hints
- Pattern
- Two pointers to reverse each word in place
- Approach
- Split by spaces or track word start/end indices. For each word, use two pointers to reverse characters.
- Complexity
- Find word boundaries, then reverse characters within each word
Solutions
=
= 0
= 0
, = , - 1
, = ,
+= 1
-= 1
= + 1
, = ,
, = ,
+= 1
-= 1
return