leetcode 1451. Rearrange Words in a Sentence(python)

描述

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.

Example 1:

Input: text = "Leetcode is cool"
Output: "Is cool leetcode"
Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
Output is ordered by length and the new first word starts with capital letter.	

Example 2:

Input: text = "Keep calm and code on"
Output: "On and keep calm code"
Explanation: Output is ordered as follows:
"On" 2 letters.
"and" 3 letters.
"keep" 4 letters in case of tie order by position in original text.
"calm" 4 letters.
"code" 4 letters.

Example 3:

Input: text = "To be or not to be"
Output: "To be or to be not"

Note:

text begins with a capital letter and then contains lowercase letters and single space between words.
1 <= text.length <= 10^5

解析

根据题意,只需要将 text 按照空格分割成字符串数组,然后按照字符串长度排序(这个过程满足长度一样的情况下按照原字符串的前后顺序排列),最后字符串用空格连起来并将首字母大写即可得到结果

解答

class Solution(object):
    def arrangeWords(self, text):
        """
        :type text: str
        :rtype: str
        """
        words = text.split(" ")
        words.sort(key = lambda x:len(x))
        res = " ".join(words).capitalize()
        return res

运行结果

Runtime: 36 ms, faster than 65.63% of Python online submissions for Rearrange Words in a Sentence.
Memory Usage: 16.4 MB, less than 92.97% of Python online submissions for Rearrange Words in a Sentence.

原题链接:https://leetcode.com/problems/rearrange-words-in-a-sentence

您的支持是我最大的动力

猜你喜欢

转载自blog.csdn.net/wang7075202/article/details/115267514