竞争性编程简单

电话簿

“电话目录”问题的详细指南和 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 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。