def arrange_words(text: str) -> str:
words = text.split()
words.sort(key=lambda word: len(word))
return ' '.join(words).capitalize()
以上代码中,我们首先将输入字符串 text
按空格拆分成单个单词。接着,利用 sort()
方法对这些单词进行排序,排序的 key 是单词的长度 len(word)
。最后,我们将排序后的单词以空格为间隔进行拼接,并将首字母大写。执行 arrange_words("Leetcode is cool")
,将返回字符串 "Is cool leetcode"。
下一篇:按单词长度筛选列表