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

Longest Word in Dictionary ใน Python: หาคำยาวที่สุดสร้างได้ทีละตัวอักษร

ได้รายการคำแทนพจนานุกรม หาคำที่ยาวที่สุดที่สร้างได้ทีละตัวอักษรจากคำอื่นในพจนานุกรม (คำนำหน้าทุกตัวต้องมีในพจนานุกรม) หากหลายคำ คืนคำที่เรียงลำดับเล็กซิโคกราฟิกน้อยที่สุด

ตัวอย่าง

["h","he","hel","hell","hello"] → "hello" (h→he→hel→hell→hello ทุกคำนำหน้ามีอยู่)

ขั้นตอนการแก้ปัญหา (Trie)

  1. สร้าง Trie ใส่คำทุกคำ
  2. แต่ละโหนดเก็บว่าเป็นปลายคำหรือไม่
  3. ค้นหาคำที่: ทุกคำนำหน้ามีอยู่ใน Trie (เป็นคำสมบูรณ์)
  4. เลือกคำที่ยาวที่สุด, ถ้าเท่ากันเลือกเรียงลำดับน้อยที่สุด

การติดตั้งใน Python

class Solution:
    def longestWord(self, words):
        self.trie = {}
        def insert(word):
            node = self.trie
            for c in word:
                if c not in node:
                    node[c] = {'#': False}
                node = node[c]
            node['#'] = True
        def search(word):
            node = self.trie
            for c in word:
                if '#' in node and not node['#']:
                    return False
                node = node[c]
            return node['#']
        for w in words:
            insert(w)
        ans = ""
        for w in words:
            if search(w) and (len(w) > len(ans) or (len(w) == len(ans) and w < ans)):
                ans = w
        return ans

ob = Solution()
print(ob.longestWord(["h","he","hel","hell","hello"]))  # hello

อินพุต / เอาต์พุต

Input: ["h","he","hel","hell","hello"]
Output: hello