C/C++教程

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

  • 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]

这篇关于[leetcode] 557. Reverse Words in a String III的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!