Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Group Anagrams ใน Python - จัดกลุ่มคำที่เป็น Anagram

สมมติว่าเรามีชุดสตริง เราต้องจัดกลุ่ม anagram รวมกัน ตัวอย่าง ["eat", "tea", "tan", "ate", "nat", "bat"] กลุ่มคือ [["ate","eat","tea"],["nat","tan"],["bat"]]

ขั้นตอนการทำงาน

  1. กำหนด res เป็น map (dictionary)
  2. วนลูป i ในอาร์เรย์สตริง:
    • x := sorted string of i แล้ว join
    • ถ้า x in result ใส่ i ลง result[x]
    • มิฉะนั้น result[x] := [i]
  3. คืนค่า values of res as list

ตัวอย่างโค้ด (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"]]