一、题目
题目描述:
输入一个单词前缀和一个字典,输出包含该前缀的单词
二、输入输出
输入描述:
单词前缀+字典长度+字典字典是一个有序单词数组输入输出都是小写
输出描述:所有包含该前缀的单词,多个单词换行输出若没有则返回-1
三、示例
示例1
输入:
b 3 a b c
输出:
b
示例2
输入:
abc 4 a ab abc abcd
输出:
abc
abcd
示例3
输入:
a 3 b c d
输出:
-1
四、要求
时间限制:C/C++ 1秒,其他语言 2秒
空间限制:C/C++262144K,其他语言524288K
64bit IO Format:%lld
五、解题思路
解题思路:
- 将输入的单词前缀和字典分别保存为变量
prefix
和列表words,数量保存为n;- 遍历字典中的每个单词,使用string.startswith()方法判断单词是否以给定的前缀开头,如果是,则将其添加到结果列表中;
- 如果结果列表为空,则返回字符串"-1";
- 输出对比结果。
六、参考代码
# -*- coding: utf-8 -*-
'''
@File : 2023-B-查字典.py
@Time : 2023/12/13 23:32:24
@Author : mgc
@Version : 1.0
@Desc : None
'''
def find_words_with_prefix(n, prefix, words):
result = []
for word in words:
if word.startswith(prefix):
result.append(word)
else:
continue
if len(result) == 0:
result.append(-1)
return result
str = input().split()
prefix = str[0]
n = int(str[1])
words = str[2:]
result = find_words_with_prefix(n, prefix, words)
for word in result:
print(word)