C++算法10:字符串频数问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xuan_zizizi/article/details/81975640

1.输入字符串,如果某字符出现次数最多,并且等于其他字符出现的总和,那么输出“YES”,其他输出NO。
例如:输入”asdff”,输出”NO”,输入”asssdf”,输出”YES”
2.代码:

# include <iostream>
# include<vector>
using namespace std;

//声明
int CalFre(const char *str, int *pFre);
int CalMax(int* pFre, int N);
//计算字母出现频数
int CalFre(const char *str, int *pFre)
{
    int len = 0;
    while (*str)
    {
        pFre[*str]++;
        //cout << pFre[*str] << endl;
        str++;
        len++;
    }
    return len;
}
//计算字符串最大频数
int CalMax(int* pFre, int N)
{
    int j = 0;
    int max = 0;
    for (int i = 0; i < N; i++)
    {
        if (max < pFre[i])
        {
            max = pFre[i];
        }
    }
    return max;
}

int main()
{
    const int N = 256;
    char str[20];
    cout << "请输入字符串:" << endl;
    cin >> str;
    int pFre[N] = { 0 };
    int len = CalFre(str, pFre);
    int max = CalMax(pFre, N);
    int other = len - max;
    //cout << max <<"  "<< len << "  " << other << endl;
    if (max == other)
    {
        cout << "YES" << endl;
    }
    else
    {
        cout << "NO" << endl;
    }
}

3.结果:

请输入字符串:
asdfghh
NO
请按任意键继续. . .
请输入字符串:
sssddf
YES
请按任意键继续. . .

猜你喜欢

转载自blog.csdn.net/xuan_zizizi/article/details/81975640