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 = "God Ding"
Output: "doG gniD"
Constraints:
1 <= s.length <= 5 * 10^4
s
contains printable ASCII characters.s
does not contain any leading or trailing spaces.s
.s
are separated by a single space.s
into words based on spaces.def reverseWords(s: str) -> str:
# Split the string into words
words = s.split()
# Reverse each word and store the results back
reversed_words = [word[::-1] for word in words]
# Join the reversed words with space separator
return ' '.join(reversed_words)
# Testing the function with the provided examples
print(reverseWords("Let's take LeetCode contest")) # "s'teL ekat edoCteeL tsetnoc"
print(reverseWords("God Ding")) # "doG gniD"
n
is the length of the string since we traverse each character to split the words.m
is the length of the word. Summed over all words, this still results in O(n).Thus, the overall time complexity is O(n), where n
is the length of the input string s
. This algorithm efficiently handles the provided constraints and should perform well within the given limits.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?