2273. Find Resultant Array After Removing Anagrams

題目

You are given a 0-indexed string array words, where words[i] consists of lowercase English letters.

In one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satisfies the conditions.

Return words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, "dacb" is an anagram of "abdc".

題目連結

思路

此題的關鍵在於判斷前後兩組字串是否由相同類型和數量的字母所組成,使用 sorted 將字串排序後即可讓所有的 anagrams 變成相同的字串,以此作為判斷依據,最後排除欲刪掉的字串即可。

Full Code

class Solution:
    def removeAnagrams(self, words: List[str]) -> List[str]:
        length = len(words)
        delIdxs = []
        for i in range(1, length):
            if sorted(words[i]) == sorted(words[i-1]):
                delIdxs.append(i)

        keepIdxs = [i for i in range(length) if i not in delIdxs]
        
        return [words[i] for i in keepIdxs]

Copyright© 2026 ZeoXer. All Rights Reserved.