题解:UVA10789 Prime Frequency

· · 题解

题意简述

给定一个字符串,找到所有出现次数为素数的字符,按字典序输出。如果没有则输出 empty

解题思路

使用 map 统计每个字符的出现次数。

使用基于范围的 for 循环遍历 map,对于每个字符,判断其出现次数是否为素数。如果是,就输出该字符。

如果没有,输出 empty

参考代码

#include <bits/stdc++.h>
using namespace std;

bool prime(int n)
{
    if(n<2)return 0;
    for(int i=2;i*i<=n;i++)
    {
        if(n%i==0)return 0;
    }
    return 1;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int T;
    cin>>T;
    for(int i=1;i<=T;i++)
    {
        string s;
        cin>>s;
        map<char,int> m;
        for(auto u:s)m[u]++;
        cout<<"Case "<<i<<": ";
        bool t=1;
        for(auto [u,v]:m)
        {
            if(prime(v))
            {
                cout<<u;
                t=0;
            }
        }
        if(t)cout<<"empty";
        cout<<'\n';
    }
    return 0;
}