LeetCode contest 189 5413. 重新排列句子中的单词
Table of Contents
一、中文版
「句子」是一个用空格分隔单词的字符串。给你一个满足下述格式的句子 text :
句子的首字母大写
text 中的每个单词都用单个空格分隔。
请你重新排列 text 中的单词,使所有单词按其长度的升序排列。如果两个单词的长度相同,则保留其在原句子中的相对顺序。
请同样按上述格式返回新的句子。
示例 1:
输入:text = "Leetcode is cool"
输出:"Is cool leetcode"
解释:句子中共有 3 个单词,长度为 8 的 "Leetcode" ,长度为 2 的 "is" 以及长度为 4 的 "cool" 。
输出需要按单词的长度升序排列,新句子中的第一个单词首字母需要大写。
示例 2:
输入:text = "Keep calm and code on"
输出:"On and keep calm code"
解释:输出的排序情况如下:
"On" 2 个字母。
"and" 3 个字母。
"keep" 4 个字母,因为存在长度相同的其他单词,所以它们之间需要保留在原句子中的相对顺序。
"calm" 4 个字母。
"code" 4 个字母。
示例 3:
输入:text = "To be or not to be"
输出:"To be or to be not"
提示:
text 以大写字母开头,然后包含若干小写字母以及单词间的单个空格。
1 <= text.length <= 10^5
二、英文版
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
三、My answer
Version 1:
class Solution: def arrangeWords(self, text: str) -> str: s_list = text.split(" ") res = "" s_dict = collections.defaultdict(lambda: []) for item in s_list: item = item.lower() s_dict[len(item)].append(item) new_s_dict = sorted(s_dict.items(), key = lambda kv:(kv[0], kv[1])) for index,(key,value) in enumerate(new_s_dict): if index == 0: if index != len(s_dict) - 1: for idx,item in enumerate(value): if idx == 0: res += (item[0].upper() + item[1:] + " ") # print(item) else: res += item + " " else: for idx,item in enumerate(value): if len(value) == 1: res += (item[0].upper() + item[1:]) elif idx == 0: res += (item[0].upper() + item[1:] + " ") # print(item) elif idx == len(value) - 1: res += item else: res += item + " " elif index == len(s_dict) - 1: for idx,item in enumerate(value): if idx == len(value) - 1: res += item else: res += item + " " else: for idx,item in enumerate(value): res += item + " " return res
Version 2:
class Solution: def arrangeWords(self, text: str) -> str: t = text.split(" ") idxs = {} for i, x in enumerate(t): x = x.lower() t[i] = x if x not in idxs: idxs[x] = collections.deque() idxs[x].append(i) t.sort(key = lambda x:(len(x), idxs[x].popleft())) t[0] = t[0][0].upper() + t[0][1:] return " ".join(t)
Version 3:
class Solution: def arrangeWords(self, text: str) -> str: s_list = text.split(" ") res = "" s_dict = collections.defaultdict(lambda: []) for item in s_list: item = item.lower() s_dict[len(item)].append(item) new_s_dict = sorted(s_dict.items(), key = lambda kv:(kv[0], kv[1])) n_list = [] # print(new_s_dict) # [(2, ['is']), (4, ['cool']), (8, ['leetcode'])] for index,(key,value) in enumerate(new_s_dict): n_list += value res += " ".join(n_list) res = res.capitalize() return res
Version 4:
class Solution: def arrangeWords(self, text: str) -> str: return " ".join(sorted(text.lower().split(), key = len)).capitalize()
四、解题报告
算法:
1、text 按照空格切分成单词数组
2、每个单词都小写化处理,并取其长度
3、按单词长度排序
4、拼接最后结果
Version 1 最繁琐,基本都是 if 规则。
Version 3 是 Version 1 的简化版。Version 1 中每一个都特殊判断是否为第一个元素,第一个元素的首字母大写,最后一个单词拼接时不带末尾的空格,其余单词后面都跟着空格。
其实可以生成最终结果 res 后,大写第一个字母即可,不用每次都判断是否是第一个元素了。
另外,如何大写第一个字母,本文中提到两种方法:
1)res += (item[0].upper() + item[1:] + " ")
2)capitalize() 函数
Version 4 就是用一句话来表示,其中排序可以直接 key = len 就是按照长度对 text 生成的 list 排序了。