classSolution: defstringMatching(self, words: List[str]) -> List[str]: result = set() length = len(words) flags = [0for i in range(length)] for i in range(length): if flags[i]: continue for j in range(i+1, length): if flags[j]: continue if len(words[i]) < len(words[j]): if words[i] in words[j]: flags[i] = 1 result.add(words[i]) else: if words[j] in words[i]: flags[j] = 1 result.add(words[j]) return result
Version 2
1 2 3 4 5 6 7 8 9 10 11
classSolution: defstringMatching(self, words: List[str]) -> List[str]: words.sort(key=len) result = set() length = len(words) for i in range(length): for j in range(i+1, length): if words[i] in words[j]: result.add(words[i]) break return result