华为OD机试C卷(100分)-掌握的单词个数(C语言)

题目描述

有一个字符串数组 words 和一个字符串 chars。

假如可以用 chars 中的字母拼写出 words 中的某个“单词”(字符串),那么我们就认为你掌握了这个单词。

words 的字符仅由 a-z 英文小写字母组成,例如 “abc”

chars 由 a-z 英文小写字母和 “?” 组成。其中英文 “?” 表示万能字符,能够在拼写时当作任意一个英文字母。例如:“?” 可以当作 “a” 等字母。

注意:每次拼写时,chars 中的每个字母和万能字符都只能使用一次。

输出词汇表 words 中你掌握的所有单词的个数。没有掌握任何单词,则输出0。

输入描述

第一行:输入数组 words 的个数,记作N。

第二行 ~ 第N+1行:依次输入数组words的每个字符串元素

第N+2行:输入字符串chars

输出描述

输出一个整数,表示词汇表 words 中你掌握的单词个数

备注

1 ≤ words.length ≤ 100
1 ≤ words[i].length, chars.length ≤ 100
所有字符串中都仅包含小写英文字母、英文问号

用例

输入 4
cat
bt
hat
tree
atach??
输出 3
说明 可以拼写字符串"cat"、“bt"和"hat”

输入 3
hello
world
cloud
welldonehohneyr
输出 2
说明 可以拼写字符串"hello"和"world"

输入 3
apple
car
window
welldoneapplec?
输出 2
说明 可以拼写字符串"apple"和“car”

题目解析

本题可以分别统计出chars和word中各字符的数量,然后遍历word每个字符c,比较word和chars中统计的c字符数量,如果word的c数量超过了chars的c数量,那么就就将超出数量计入diff中。
最终比较diff和chars中万能字符‘?’的数量,如果chars中万能字符‘?’的数量 >= diff,那么说明chars可以使用万能字符补足不同部分,即可以学会word。

#include <stdio.h>
#include <stdlib.h>
#define MAX(a,b) (a>b?a:b)

int countCharacters(char** words, int wordsSize, char* chars);
int* charStatistic(const char* s) {
    int* cnts = (int*) calloc(128, sizeof(int));

    int i = 0;
    while(s[i] != '\0') {
        cnts[s[i]]++;
        i++;
    }

    return cnts;
}

int main()
{
     int n;
     char words[100][101];
     char chars[101];
     scanf("%d",&n);
     for(int i=0;i<n;i++){
          scanf("%s",words[i]);
          //gets(words[i]);

     }
     //gets(chars);
     scanf("%s",chars);
     int ans = 0;

    // 统计chars字符串中各字符的数量
    int* cnts_char = charStatistic(chars);

    for(int i=0; i<n; i++) {
        int diff = 0;

        // 统计word字符串中各字符的数量
        int* cnt_word = charStatistic(words[i]);

        for(int j=0; j<128; j++) {
            // 记录word的某字符超过chars的对应字符出现的数量
            diff += MAX(cnt_word[j] - cnts_char[j], 0);
        }

        if(diff <= cnts_char['?']) {
            ans++;
            // puts(words[i]);
        }
    }
   printf("%d",ans);
    return 0;
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我不会起名字呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值