解题思路
排序之后就是字典序了,遇到单个字符,加到集合里,多个字符则看最后一个字符之前的字符是否已经在集合里,在的话,加进集合里,不在的话,可以直接不管了,因为已经排序,说明肯定无法一步一步的达到这个字符串,再用两个变量,保存首次遇到的最长长度,最后返回(有点重复代码)
class Solution: def longestWord(self, words: List[str]) -> str: words.sort() print(words) words_set = set() max_words = '' max_count = 0 for word in words: if len(word) == 1: words_set.add(word) if len(word) > max_count: max_words = word max_count = len(word) elif word[:-1] in words_set: words_set.add(word) if len(word) > max_count: max_words = word max_count = len(word) return max_words