在 Python 中对字谜进行分组

pythonserver side programmingprogramming更新于 2025/10/25 18:20:17

假设我们有一组字符串。我们必须将字谜分组在一起。因此,如果 ["eat", "tea", "tan", "ate", "nat", "bat"],则组为 [["ate","eat","tea"],["nat","tan"],["bat"]]

要解决这个问题,我们将遵循以下步骤 −

  • 将 res 定义为 map
  • for i in string array
    • x := x and join, sorted string of i
    • if x in result
      • insert i in result[x]
    • else result[x] := [i]
  • 以列表形式返回 res 的值

示例 (Python)

让我们看下面的实现,以便更好地理解 −

class Solution:
   def groupAnagrams(self, strs):
      result = {}
      for i in strs:
         x = "".join(sorted(i))
         if x in result:
            result[x].append(i)
         else:
            result[x] = [i]
      return list(result.values())
ob1 = Solution()
print(ob1.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))

输入

["eat", "tea", "tan", "ate", "nat", "bat"]

输出

[["ate","eat","tea"],["nat","tan"],["bat"]]

相关文章


有用资源