LeetCode 题解工作台
移除字母异位词后的结果数组
给你一个下标从 0 开始的字符串数组 words ,其中 words[i] 由小写英文字符组成。 在一步操作中,需要选出任一下标 i ,从 words 中 删除 words[i] 。其中下标 i 需要同时满足下述两个条件: 0 words[i - 1] 和 words[i] 是 字母异位词 。 只要…
4
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们首先将 加入答案数组,然后从 开始遍历,如果 $\textit{words}[i - 1]$ 和 不是字母异位词,我们就将 加入答案数组。 问题转换为判断两个字符串是否是字母异位词,我们定义一个辅助函数 $\textit{check}(s, t)$ 来实现这个功能。如果 和 不是字母异位词,我们就返回 ,否则返回 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的字符串数组 words ,其中 words[i] 由小写英文字符组成。
在一步操作中,需要选出任一下标 i ,从 words 中 删除 words[i] 。其中下标 i 需要同时满足下述两个条件:
0 < i < words.lengthwords[i - 1]和words[i]是 字母异位词 。
只要可以选出满足条件的下标,就一直执行这个操作。
在执行所有操作后,返回 words 。可以证明,按任意顺序为每步操作选择下标都会得到相同的结果。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。例如,"dacb" 是 "abdc" 的一个字母异位词。
示例 1:
输入:words = ["abba","baba","bbaa","cd","cd"] 输出:["abba","cd"] 解释: 获取结果数组的方法之一是执行下述步骤: - 由于 words[2] = "bbaa" 和 words[1] = "baba" 是字母异位词,选择下标 2 并删除 words[2] 。 现在 words = ["abba","baba","cd","cd"] 。 - 由于 words[1] = "baba" 和 words[0] = "abba" 是字母异位词,选择下标 1 并删除 words[1] 。 现在 words = ["abba","cd","cd"] 。 - 由于 words[2] = "cd" 和 words[1] = "cd" 是字母异位词,选择下标 2 并删除 words[2] 。 现在 words = ["abba","cd"] 。 无法再执行任何操作,所以 ["abba","cd"] 是最终答案。
示例 2:
输入:words = ["a","b","c","d","e"] 输出:["a","b","c","d","e"] 解释: words 中不存在互为字母异位词的两个相邻字符串,所以无需执行任何操作。
提示:
1 <= words.length <= 1001 <= words[i].length <= 10words[i]由小写英文字母组成
解题思路
方法一:模拟
我们首先将 加入答案数组,然后从 开始遍历,如果 和 不是字母异位词,我们就将 加入答案数组。
问题转换为判断两个字符串是否是字母异位词,我们定义一个辅助函数 来实现这个功能。如果 和 不是字母异位词,我们就返回 ,否则返回 。
在函数 中,我们首先判断 和 的长度是否相等,如果不相等,我们就返回 。否则,我们用一个长度为 的数组 来统计 中每个字符出现的次数,然后遍历 中的每个字符,将 减 ,如果 小于 ,我们就返回 。如果正常遍历完 中的每个字符,说明 和 是字母异位词,我们返回 。
时间复杂度 ,空间复杂度 。其中 是数组 的长度,而 是字符集,这里是小写英文字母,所以 。
class Solution:
def removeAnagrams(self, words: List[str]) -> List[str]:
def check(s: str, t: str) -> bool:
if len(s) != len(t):
return True
cnt = Counter(s)
for c in t:
cnt[c] -= 1
if cnt[c] < 0:
return True
return False
return [words[0]] + [t for s, t in pairwise(words) if check(s, t)]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Understanding of array scanning techniques and hash map usage.
- question_mark
Efficiency in detecting anagrams using frequency counts or sorting.
- question_mark
Ability to optimize for space and time complexity while solving.
常见陷阱
外企场景- error
Failing to recognize the need for an efficient anagram check (sorting or hash map).
- error
Not handling edge cases, like when no words are anagrams.
- error
Overcomplicating the solution with unnecessary operations or data structures.
进阶变体
外企场景- arrow_right_alt
Allowing for a custom comparator instead of using frequency counts.
- arrow_right_alt
Modifying the input in place without using extra space.
- arrow_right_alt
Handling case sensitivity or extending the problem to a larger character set.