【华为机考模拟题】Words、Vowel、计算字符串重新排列数

目录

一、Words

二、Vowel

三、计算字符串重新排列数


一、Words

每个句子由多个单词组成,句子中的每个单词的长度都可能不一样,假设每个单词的长度 Ni 为该单词的重量,你需要做的就是给出整个句子的平均重量 V

输入 : Who Love Solo
输出 :3.67

统计单词数ans和字母数count,答案就是ans/count

复制代码
int main() {
    string words;
    getline(cin, words);
    float ans = 0, count = 1;
    for (auto &c: words) {
        if (c == ' ')
            ++count;
        else
            ++ans;
    }
    cout.precision(2);
    cout << fixed << ans / count;
    return 0;
}

二、Vowel

solo 从小就对英文字母非常感兴趣,尤其是元音字母(a,e,i,o,u,A,E,I,O,U),他在写日记的时候都会把元音字母写成大写的,辅音字母则都写成小写,虽然别人看起来很别扭,但是 solo 却非常熟练。你试试把一个句子翻译成 solo 写日记的习惯吧。

输入 : Who Love Solo
输出 :whO lOvE sOlO

是元音字母的变成大写,其他的变成小写

复制代码
int main() {
    string solo = "aeiouAEIOU";
    string words;
    getline(cin, words);
    for (auto &c: words) {
        if (solo.find(c) != string::npos)
            c = toupper(c);
        else
            c = tolower(c);
    }
    cout << words;
    return 0;
}

三、计算字符串重新排列数

给定一个只包含大写英文字母的字符串 S,要求给出对 S 重新排列的所有不相同的排列数。

如:S 为 ABA,则不同的排列有 ABA、AAB、BAA 三种。

输入 : "ABA"
输出: 3

输入 : "AABBCC"
输出: 90

回顾高中数学排列组合的知识,假设没有相同的字符,如ABCD,那么排列数就是全排列A44,即!4,如果有相同字符,那么我们实际上是多乘了一个排列数,这个排列数的存在是因为我们把相同的字符当成不同的字符来排列,因此我们再计算一次这个排序数,即相同字符的排序数,当成不同字符来计算,然后除去这个数

复制代码
#include<iostream>
#include<map>
using namespace std;

int fact(int n) {
    int result = 1;
    for (int i = 2; i <= n; ++i)
        result *= i;
    return result;
}

int main() {
    string words;
    getline(cin, words);
    map<char, int> count;
    for (auto c: words) {
        ++count[c];
    }
    int ans = 1;
    for (auto &&it = count.begin(); it != count.end(); ++it) {
        ans *= fact(it->second);
    }
    cout << fact(words.size()) / ans;
    return 0;
}
相关推荐
不想写代码的星星1 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛2 天前
delete又未完全delete
c++
祈安_2 天前
C语言内存函数
c语言·后端
端平入洛3 天前
auto有时不auto
c++
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
czy87874754 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
王码码20354 天前
Flutter for OpenHarmony:socket_io_client 实时通信的事实标准(Node.js 后端的最佳拍档) 深度解析与鸿蒙适配指南
android·flutter·ui·华为·node.js·harmonyos
蜡笔小马4 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost