Leetcode 2273. Find Resultant Array After Removing Anagrams

Problem

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".

Algorithm

The number of occurrences of each letter forms a tuple for comparison.

Code

python3 复制代码
class Solution:
    def removeAnagrams(self, words: List[str]) -> List[str]:
        def letters(word: str):
            cnt = [0] * 26
            for ch in word:
                cnt[ord(ch) - ord('a')] += 1
            return tuple(cnt)

        pre, ans = None, []
        for word in words:
            s = letters(word)
            if s != pre:
                ans.append(word)
                pre = s
        
        return ans
相关推荐
2401_8318249617 分钟前
代码性能剖析工具
开发语言·c++·算法
Sunshine for you1 小时前
C++中的职责链模式实战
开发语言·c++·算法
qq_416018721 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563241 小时前
模板代码生成工具
开发语言·c++·算法
2401_831920742 小时前
C++代码国际化支持
开发语言·c++·算法
m0_672703312 小时前
上机练习第51天
数据结构·c++·算法
ArturiaZ2 小时前
【day60】
算法·深度优先·图论
2401_851272992 小时前
自定义内存检测工具
开发语言·c++·算法
☆5663 小时前
C++中的命令模式
开发语言·c++·算法
仰泳的熊猫3 小时前
题目2577:蓝桥杯2020年第十一届省赛真题-走方格
数据结构·c++·算法·蓝桥杯