其他分享
首页 > 其他分享> > [leetcode] 557. Reverse Words in a String III

[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:

思路

分割字符串为数组,逆转每个元素,再合并数组为字符串。

神奇算法:分割字符串为数组,逆转数组,再合并数组为字符串,再逆转字符串

代码

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]

标签:word,String,557,数组,str,字符串,Input,Words,words
来源: https://www.cnblogs.com/frankming/p/15937980.html