zoukankan      html  css  js  c++  java
  • 【leetcode】1451. Rearrange Words in a Sentence

    题目如下:

    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"

    Constraints:

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

    解题思路:也没什么好说的,分割后排序即可。

    代码如下:

    class Solution(object):
        def arrangeWords(self, text):
            """
            :type text: str
            :rtype: str
            """
            text = text.lower()
            words = text.split(' ')
            for i in range(len(words)):
                words[i] = (words[i],i)
    
            def cmpf(item1,item2):
                if len(item1[0]) != len(item2[0]):
                    return len(item1[0]) - len(item2[0])
                return item1[1] - item2[1]
    
            words.sort(cmp=cmpf)
    
            res = ''
            for i in words:
                res += i[0]
                res += ' '
            res = res[:-1]
    
            return res.capitalize()
            
  • 相关阅读:
    C#之正则表达式、异常处理和委托与事件
    C#之interface接口
    C#之类与对象
    C#第一次的Hello World
    第一次用博客
    用Visual Studio 2012+Xamarin搭建C#开发Andriod的环境
    cocos2dx 3.x for lua "异步加载"实现过程
    cocos2dx 3.x c++代码打包给lua调用过程(mac)
    cocos2dx 3.x lua 网络加载并且保存资源(unix、linux)
    path类和directory类对文件的路径或目录进行操作
  • 原文地址:https://www.cnblogs.com/seyjs/p/13046780.html
Copyright © 2011-2022 走看看