Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Từ Dài Nhất Trong Từ Điển (Longest Word in Dictionary) trong Python


Giả sử ta có một danh sách các từ đại diện cho một Từ điển tiếng Anh, ta cần tìm từ dài nhất trong danh sách từ cho trước có thể được xây dựng từng ký tự một bởi các từ khác trong words. Nếu có nhiều đáp án có thể, trả về từ dài nhất có thứ tự từ điển nhỏ nhất. Nếu không có đáp án, trả về chuỗi rỗng.

Ví dụ, nếu đầu vào là ["h","he","hel","hell", "hello"], thì đầu ra sẽ là "hello"

Để giải quyết, ta thực hiện các bước sau:

  • trie := một map mới
  • Định nghĩa hàm insert(). Nhận tham số word
  • now := trie
  • Với mỗi c trong word, thực hiện:
    • Nếu c không trong now:
      • now[c] = {'#', False}, thì
    • now := now[c]
    • now['#'] := True
  • Định nghĩa hàm search(). Nhận tham số word
  • now := trie
  • Với mỗi c trong word, thực hiện:
    • Nếu '#' trong now và not now['#'] là True, thì:
      • Trả về false
    • now := now[c]
    • Trả về now['#']
  • Với mỗi word trong words, thực hiện:
    • Gọi insert(word)
  • ans := chuỗi rỗng
  • Với mỗi word trong words, thực hiện:
    • Nếu search(word) và (độ dài word > độ dài ans hoặc (độ dài word bằng độ dài ans và word < ans)), thì:
      • ans := word
  • Trả về ans

Hãy xem triển khai sau để hiểu rõ hơn:

Ví dụ

class Solution:    def longestWord(self, words):       self.trie = {}    def insert(word):       now = self.trie       for c in word:           if c not in now: now[c] = {'#': False}             now = now[c]           now['#'] = True    def search(word):       now = self.trie       for c in word:           if '#' in now and not now['#']: return False             now = now[c]           return now['#']           for word in words:             insert(word)           ans = ""           for word in words:             if (search(word) and (len(word) > len(ans) or (len(word) == len(ans) and word     < ans))):           ans = word       return ans ob = Solution() print(ob.longestWord(["h","he","hel","hell", "hello"]))

Đầu vào

["h","he","hel","hell", "hello"]

Đầu ra

hello