【华为机考模拟题】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;
}
相关推荐
tt55555555555510 分钟前
字符串与算法题详解:最长回文子串、IP 地址转换、字符串排序、蛇形矩阵与字符串加密
c++·算法·矩阵
rainFFrain1 小时前
Boost搜索引擎项目(详细思路版)
网络·c++·http·搜索引擎
long_run2 小时前
C++之模板函数
c++
NuyoahC2 小时前
笔试——Day43
c++·算法·笔试
彷徨而立3 小时前
【C++】 using声明 与 using指示
开发语言·c++
一只鲲3 小时前
48 C++ STL模板库17-容器9-关联容器-映射(map)多重映射(multimap)
开发语言·c++
智践行4 小时前
C++11 智能指针:`std::unique_ptr`、`std::shared_ptr`和`std::weak_ptr`
c++
智践行4 小时前
C++11之后的 Lambda 表达式 以及 `std::function`和`std::bind`
c++
智践行4 小时前
C++11移动语义‘偷梁换柱’实战
c++
祁同伟.5 小时前
【C++】模版(初阶)
c++