LeetCode刷题笔记第1859题:将句子排序
题目:
想法:
通过空格切分句子为单词列表,根据最后每个单词的最后一个数字在新的列表中存入相对应的位置,返回按照新列表中的顺序拼接的句子。
class Solution:
def sortSentence(self, s: str) -> str:
word_list = s.split(" ")
result_list = [0] * len(word_list)
for item in word_list:
result_list[int(item[-1])-1] = item[:-1]
return " ".join(result_list)
因为要遍历整个列表,时间复杂度O(n)
因为创建了一个新的列表,空间复杂度O(n)