[leetcode] 557. Reverse Words in a String III
题目
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.- There is at least one word in
s
. - All the words in
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]
本文来自博客园,作者:frankming,转载请注明原文链接:https://www.cnblogs.com/frankming/p/15937980.html