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
相关推荐
Omigeq15 分钟前
1.4 - 曲线生成轨迹优化算法(以BSpline和ReedsShepp为例) - Python运动规划库教程(Python Motion Planning)
开发语言·人工智能·python·算法·机器人
网络工程小王37 分钟前
【大模型(LLM)的业务开发】学习笔记
人工智能·算法·机器学习
y = xⁿ38 分钟前
【Leet Code 】滑动窗口
java·算法·leetcode
WBluuue41 分钟前
数据结构与算法:二项式定理和二项式反演
c++·算法
nianniannnn41 分钟前
力扣104.二叉树的最大深度 110. 平衡二叉树
算法·leetcode·深度优先
_深海凉_1 小时前
LeetCode热题100-只出现一次的数字
算法·leetcode·职场和发展
nianniannnn1 小时前
力扣206.反转链表 92.反转链表II
算法·leetcode·链表
澈2071 小时前
哈希表实战:从原理到手写实现
算法·哈希算法
旖-旎1 小时前
哈希表(存在重复元素||)(4)
数据结构·c++·算法·leetcode·哈希算法·散列表
Run_Teenage1 小时前
Linux:认识信号,理解信号的产生和处理
linux·运维·算法