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 * 104
s
contains printable ASCII characters.s
does not contain any leading or trailing spaces.s
.s
are separated by a single space.分割字符串为数组,逆转每个元素,再合并数组为字符串。
神奇算法:分割字符串为数组,逆转数组,再合并数组为字符串,再逆转字符串
python版本:
class Solution: def reverseWords(self, s: str) -> str: words=[word[::-1] for word in s.split()] return ' '.join(words) # 神奇算法 class Solution: def reverseWords(self, s: str) -> str: return ' '.join(s.split()[::-1])[::-1]