题目:掌握的单词个数
题目描述
有一个字符串数组Q words 和一个字符串 chars,假如可以用 chars 中的字母拼写出 words 中的某个“单词”(字符串),那么我们就认为你掌握了这个单词。words 的字符仅由 a-z 英文小写字母组成,例如"abc" chars 由 a-z 英文小写字母和 "?“组成。其中英文”?“表示万能字符,能够在拼写时当作任意一个英文字母Q。例如:”?"可以当作"a"等字母。
注意:每次拼写时,chars 中的每个字母和万能字符都只能使用一次。
输出词汇表 words 中你掌握的所有单词的个数。没有掌握任何单词,则输出0.
输入描述
第一行:输入数组 words 的个数,记作N。
第二行~第N+1行:依次输入数组words的每个字符串元素
第N+2行:输入字符串 chars
输出描述
输出一个整数,表示词汇表 words 中你掌握的单词个数
用例1
输入
4
cat
bt
hat
tree
atach??
输出
3
说明:可以拼写字符串"cat"、"bt"和"hat’
用例2
输入
3
hello
world
cloud
welldonehohneyr
输出
2
说明:可以拼写字符串"hello"和"world"
java实现
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] danci = new String[n];
for (int i = 0; i < n; i++) {
danci[i] = sc.next();
}
String chars = sc.next();
System.out.println(getResult(danci, n, chars));
}
public static int getResult(String[] danci, int n, String chars) {
int n = 0;
int[] cnt_chars = charStatistic(chars);
for (int i = 0; i < n; i++) {
int diff = 0;
int[] cnt_word = charStatistic(danci[i]);
for (int j = 0; j < 128; j++) {
diff += Math.max(cnt_word[j] - cnt_chars[j], 0);
}
if (diff <= cnt_chars['?']) {
n++;
// System.out.println(danci[i]);
}
}
return n;
}
public static int[] charStatistic(String s) {
int[] counts = new int[128];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
counts[c] += 1;
}
return counts;
}
}
python实现
n = int(input())
danci = []
for i in range(n):
danci.append(input())
chars = input()
def charStatistic(s):
counts = [0] * 128
for c in s:
counts[ord(c)] += 1
return counts
def getResult():
n = 0
cnt_chars = charStatistic(chars)
for word in danci:
diff = 0
cnt_word = charStatistic(word)
for j in range(128):
diff += max(cnt_word[j] - cnt_chars[j], 0)
if diff <= cnt_chars[ord('?')]:
n += 1
# print(word)
return n
print(getResult())
c++实现
#include <bits/stdc++.h>
int test(vector<string> &danci, string &chars) {
int ans = 0;
int cnt_chars[128] = {0};
for (const auto &c: chars) {
cnt_chars[c]++;
}
for (const auto &word: danci) {
int n = 0;
int cnt_word[128] = {0};
for (const auto &c: word) {
cnt_word[c]++;
}
for (int j = 0; j < 128; j++) {
n += max(cnt_word[j] - cnt_chars[j], 0);
}
if (n <= cnt_chars['?']) {
ans++;
}
}
return ans;
}
int main() {
int n;
cin >> n;
vector<string> danci;
for (int i = 0; i < n; i++) {
string word;
cin >> word;
danci.emplace_back(word);
}
string chars;
cin >> chars;
cout << test(danci, chars) << endl;
return 0;
}