题目描述:科丁国王认为,在 0-9 这 10 个一位数字中,只有 n 个是完美无瑕的,而只由它们组成的多位数,可以称为优美的数字。现在告诉你科丁国王认为的 n 个完美无瑕的一位数字,再给你m个多位数,让你找出这 m 个多位数中有哪些数是优美的数字。
输入格式
输入文件名:number.in
输入共 3 行,第一行两个整数 n 和 m(1<=n<=10,1<=m<=1000)第二行 n 个互不相同的一位数字,空格隔开表示国王认为的完美无瑕的一位数字第三行 m 个多位数,空格隔开,每个数字的范围不超过 10 的 9 次方输出格式
输出文件名:number.out
输出若干行,每行一个整数,表示你所找到的优美的数字,输出顺序和输入顺序一致如果找不到优美的数字,输出一个“none”
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
unordered_set<char> perfect_digits;
for (int i = 0; i < n; i++) {
char c;
cin >> c;
perfect_digits.insert(c);
}
for (int i = 0; i < m; i++) {
string s;
cin >> s;
bool is_perfect = true;
for (char c : s) {
if (perfect_digits.find(c) == perfect_digits.end()) {
is_perfect = false;
break;
}
}
if (is_perfect) {
cout << s << endl;
} else {
cout << "none" << endl;
}
}
return 0;
}
首先读入 n 和 m,以及 n 个完美无瑕的一位数字,使用一个 unordered_set 存储。
然后循环读入 m 个多位数,对于每个多位数,遍历其每一位数字,如果有任意一位数字不在完美无瑕数字的集合中,说明该多位数不是优美的数字,将 is_perfect 标记为 false。如果整个多位数的所有数字都在完美无瑕数字的集合中,说明该多位数是优美的数字,输出该多位数。
时间复杂度为 O(m * len),其中 len 为多位数的最大长度。
该回答引用GPTᴼᴾᴱᴺᴬᴵ
一种可能的 Python 实现如下:
def is_beautiful_number(number, beautiful_digits):
# 判断数字 number 是否是优美的数字
for digit in str(number):
if digit not in beautiful_digits:
return False
return True
with open('number.in', 'r') as f:
# 读入数据
n, m = map(int, f.readline().split())
beautiful_digits = set(f.readline().split())
numbers = list(map(int, f.readline().split()))
# 遍历多位数,找出优美的数字
beautiful_numbers = []
for number in numbers:
if is_beautiful_number(number, beautiful_digits):
beautiful_numbers.append(number)
# 输出结果
if beautiful_numbers:
for number in beautiful_numbers:
print(number)
else:
print('none')
最后,如果 beautiful_numbers 列表不为空,就按输入顺序输出其中的每一个数字。否则,输出字符串 'none'。
不知道你这个问题是否已经解决, 如果还没有解决的话: