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

发布于:2024-05-08 ⋅ 阅读:(40) ⋅ 点赞:(0)

目录

一、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;
}