競賽程式設計簡單

電話簿

“電話目錄”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 phone_directory(contacts, query),它接受唯一字串 contacts 的列表和查詢字串 query。它應該傳回字串列表的列表,其中第 i 列表包含與 query 前綴匹配的已排序聯絡人,最長長度為 i+1(索引為 1)。如果沒有符合的聯絡人,則傳回該前綴的空列表。

約束條件
  • 1 <= len(contacts) <= 100
  • 1 <= len(query) <= 20
  • All strings consist of lowercase English letters.

範例

Example 1
Input
phone_directory(['geeikist', 'geeksforgeeks', 'geeksfortest', 'geeky'], 'gee')
Output
[['geeikist', 'geeksforgeeks', 'geeksfortest', 'geeky'], ['geeikist', 'geeksforgeeks', 'geeksfortest', 'geeky'], ['geeikist', 'geeksforgeeks', 'geeksfortest', 'geeky']]
Explanation

For 'g', 'ge', and 'gee', all 4 contacts match prefix and are returned in sorted order.

Example 2
Input
phone_directory(['mobile', 'mouse', 'moneypot', 'monitor', 'mousepad'], 'mouse')
Output
[['mobile', 'monitor', 'moneypot', 'mouse', 'mousepad'], ['mobile', 'monitor', 'moneypot', 'mouse', 'mousepad'], ['mouse', 'mousepad'], ['mouse', 'mousepad'], ['mouse', 'mousepad']]
Explanation

For prefix 'm' and 'mo', all contacts match. For 'mou', 'mous', and 'mouse', only 'mouse' and 'mousepad' match.

Need a Hint?
考慮使用 Trie 特定的資料結構,例如集合或堆疊。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。