Given a string s
, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Constraints:
- $1\leq s.length \leq 5*104$
s
contains printable ascii characterss
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
Input: s = "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Input: s = "God Ding" Output: "doG gniD"
Not too much to write here.
With Python we can simply split the string by space, do reverse and then join then back together with a space.
def reverseWords(s):
"""
:type s: str
:rtype: str
"""
return " ".join([w[::-1] for w in s.split(" ")])
# tests
s = "t"
target = "t"
print(reverseWords(s) == target)
s = "Let's take LeetCode contest"
target = "s'teL ekat edoCteeL tsetnoc"
print(reverseWords(s) == target)
O(N)
, N
is length of s
.
O(N)
, N
is length of s
, as we need to store the temporary reversed list of words.
nil
.
<<imports for typing>>
I think in an interview I’d just go with regex to reduce these two questions in the the original question and solve it.