题目
解法1:
同时sort单词长度和index
class Solution:def arrangeWords(self, text: str) -> str:text = text.split()len_ind_list = []for i, word in enumerate(text):len_ind_list.append((len(word),i,word))len_ind_list.sort(key = lambda x: (x[0],x[1]))ans = ''for i, (_len,ind,word) in enumerate(len_ind_list):if i == 0:ans += word[0].upper() + word[1:]#print(word[0].upper())else:ans += word.lower()ans += ' 'return ans[:-1]
解法2:
事实证明sort函数在长度相同的情况下会自动让index升序,所以不需要上面sort的这么麻烦,这里有两个小技巧:
- 根据元素的长度排序可以直接用key=len,无需lambda
- 这种加空格的做法直接用join函数
text = text.lower()s = text.split()s.sort(key=len) res = ' '.join(s)res = res.capitalize()print(res)return res
参考链接:https://leetcode.com/problems/rearrange-words-in-a-sentence/discuss/924848/95-faster-Python-Very-easy-to-understand