2020.8 复习 7-5 2018Final简单字符串string处理(三人行)//PTA

题意

凤湖中学在这学期流行一个名为“三人行”英文诗赛。比赛中,"老师"先说一个英语单词作为主题词,然后三位“路人"各说一句英语诗,看谁的诗更符合主题词。以主题词中的字母在诗中的出现次数作为符合度。在评价符合度时:不区分大小写;只关注英语字母(a-z),忽略其它字母。如果某句诗所含英语字母数大于20个,则分别用该诗句的前20个英语字母和后20个英语字母来计算符合度,并取两者之较大值作为实际的符合度。

输入格式:

输入一共有4行,第1行是一个主题词,接下来的3行,各输入一句英语诗句。

输出格式:

输出一共有3行,是各句诗的符合度。

输入样例:

soon
Some tours are doomed to return, Some doors are destined to open then to close.
Days fly by. Soon I need to remove this page, and hang up a new year.
Summer isn't far behind, And another year has passed.

输出样例:

8
7
5
思路:

一开始读错题意了,以为是判断这个单词在句子中出现的次数//太蠢了😭 其实是判断给出单词的字母在句子中出现的次数

  1. 我们可以用set保存输入的单词的每个字母

    用set可以保证没有重复字母,避免超时

    一定要把输入的单词也全都转成小写(全都大写也行,我是写了小写)

    一开始就是没有全部转小写然后只过了两个点

  2. 对句子进行处理,把每个句子都转成小写

  3. 用两个循环对前20和后20个字母进行判断

#include <bits/stdc++.h>
using namespace std;
int Count(string s, set<char> a)
{
    int before = 0, after = 0;
    int loc = 0;
    transform(s.begin(), s.end(), s.begin(), ::tolower);
    for (auto it = s.begin(); it != s.end(); it++)
    {
        if (*it >= 'a' && *it <= 'z')//不对其他字符进行计数和处理
        {
            loc++;
            for (auto it2 : a)
            {
                if (*it == it2)
                {
                    before++;
                    break;
                }
            }
        }
        if (loc == 20)
            break;
    }
    loc = 0;
    for (auto it = s.rbegin(); it != s.rend(); it++)
    {
        if (*it >= 'a' && *it <= 'z')
        {
            loc++;
            for (auto it2 : a)
            {
                if (*it == it2)
                {
                    after++;
                    break;
                }
            }
        }
        if (loc == 20)
            break;
    }
    return before >= after ? before : after;
}
int main()
{
    string judge;
    getline(cin, judge);//这句不能用cin>>judge
    transform(judge.begin(),judge.end(),judge.begin(),::tolower);//很重要,一定要统一
    set<char> a;//保证不重复字母
    for (auto it : judge)
    {
        a.insert(it);
    }
    for (int i = 0; i < 3; ++i)
    {
        string s;
        getline(cin, s);
        cout << Count(s, a) << endl;
    }
    return 0;
}
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值