LeetCode 1451 Rearrange Words in a Sentence (Python)

Posted by 小明MaxMing on May 17, 2020

题目

Given a sentence text (A sentence is a string of space-separated words) in the following format:

  • First letter is in upper case.
  • Each word in text are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.

Return the new text following the format shown above.

解题思路

先split出每个单词,按单词数排序,拼回去再把首字母大写

代码

class Solution:
    def arrangeWords(self, text: str) -> str:
        return " ".join(sorted(text.split(), key=len)).capitalize()

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅