问题 13:分组字母异位词

发布: (2026年2月10日 GMT+8 10:53)
3 分钟阅读
原文: Dev.to

Source: Dev.to

概述

任务是编写一个函数,从给定的字符串列表中将相互是字母异位词的单词分组。
字母异位词是通过重新排列另一个单词或短语的字母而形成的单词或短语,且每个原始字母恰好使用一次。

示例

group_anagrams(['listen', 'silent', 'hello', 'world', 'enlist'])

预期输出

[['listen', 'silent', 'enlist'], ['hello'], ['world']]

解决方案

Python 实现

def group_anagrams(words):
    """
    Groups words that are anagrams of each other.
    """
    # Edge case: None or empty input
    if not words:
        return []

    anagram_groups = {}

    for word in words:
        # Create a case‑insensitive, sorted tuple as the dictionary key
        key = tuple(sorted(word.lower()))

        if key in anagram_groups:
            anagram_groups[key].append(word)
        else:
            anagram_groups[key] = [word]

    return list(anagram_groups.values())

测试

print(group_anagrams(['listen', 'silent', 'hello', 'world', 'enlist']))
# Output: [['listen', 'silent', 'enlist'], ['hello'], ['world']]

解释

  1. 处理边界情况 – 如果 wordsNone 或为空,返回空列表。
  2. 为每个单词创建签名
    • 将单词转换为小写 (word.lower()) 以实现不区分大小写的分组。
    • 对其字符进行排序 (sorted(...))。
    • 将排序后的列表转换为元组,以便用作字典键。
  3. 分组单词 – 使用字典 (anagram_groups);每个键是签名元组,值是共享该签名的单词列表。
  4. 返回分组 – 将字典的 values 视图转换为列表并返回。

逐步演示 ['listen', 'silent', 'hello']

步骤单词键(排序元组)操作
1listen('e', 'i', 'l', 'n', 's', 't')新条目 → {'...': ['listen']}
2silent('e', 'i', 'l', 'n', 's', 't')键已存在 → 追加 → {'...': ['listen', 'silent']}
3hello('e', 'h', 'l', 'l', 'o')新条目 → {'...': ['hello']}

结果:[['listen', 'silent'], ['hello']]

祝编码愉快! 💻

0 浏览
Back to Blog

相关文章

阅读更多 »

特殊字符 | C++ 初学者

String 和特殊字符 Escape 符号用于在字符串或文本中编写特殊命令/字符。' ' – 在引号内部写入引号。