华为od机试D卷100分题-万能单词拼写
我的方法效率可能不是最优,但比较容易理解,同时,思路解析中的变量可能与代码名称不同,仅作参考
题目:
思路与解析:
1、输入n和n个字符串words,再输入字符串chars
2、先定义一个变量count记录有多少个能拼写的单词
3、因为words只有小写字母,chars只有小写字母加‘?’。
用一个数组arr1[27]存放chars中小写字母和'?'出现的次数
遍历所有字符串words,每次定义一个arr2[26]记录words中小写字母出现次数。
4、对arr1和arr2进行比较,若arr2中字符次数大于arr1字符次数,将其差值相加(比如sum+=arr2[i]-arr1[i])
5、如果差值和小于或者等于'?'的个数,说明可以用'?'转换,count++;否则无法拼写,不统计。
6、最后输出count即可。
代码如下:
#include <iostream>
#include<string>
using namespace std;
int main()
{
int n,ans=0;
cin >> n;
string str[100];
string mod;
for (int i = 0; i < n; i++)
cin >> str[i];
cin >> mod;
int a[27] = { 0 };
for (int i = 0; i < mod.size(); i++) {
if (mod[i] == '?')
a[26]++;
else
a[mod[i] - 'a']++;
}
for (int i = 0; i < n; i++) {
int dis = 0;
int b[26] = { 0 };
for (int j = 0; j < str[i].size(); j++)
b[str[i][j]-'a']++;
for (int j = 0; j < 26; j++) {
dis += a[j] >= b[j] ? 0 : b[j] - a[j];
}
if (dis <= a[26])
ans++;
}
cout << ans << endl;
}
#软件开发笔面经##牛客在线求职答疑中心#
