PAT A1071 Speech Patterns

PAT A1071 Speech Patterns

题目描述

People often have a preference among synonyms of the same word. For example, some may prefer “the police”, while others may prefer “the cops”. Analyzing such patterns can help to narrow down a speaker’s identity, which is useful when validating, for example, whether it’s still the same person behind an online avatar.

Now given a paragraph of text sampled from someone’s speech, can you find the person’s most commonly used word?

题解

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <string>

using namespace std;

bool alphanumerical(char a)
{
    
    
    if (a >= '0' && a <= '9')
        return true;
    if (a >= 'a' && a <= 'z')
        return true;
    if (a >= 'A' && a <= 'Z')
        return true;

    return false;
}

//转为小写
string lower(string str)
{
    
    
    for (int i = 0;i < str.length();i++)
    {
    
    
        if (str[i] >= 'A' && str[i] <= 'Z')
        {
    
    
            str[i] -= 'A' - 'a';
        }
    }
    return str;

}

bool cmp(const pair<string, int>&a, const pair<string, int> &b)
{
    
    
    if (a.second != b.second)
        return a.second > b.second;
    else
        return a.first < b.first;
}

int main()
{
    
    
    string str;
    map<string, int> count;
    getline(cin, str);
    for (int i = 0;i < str.length();)
    {
    
    
        int j = i;
        while (alphanumerical(str[j]))
            j++;
        string tmp = str.substr(i, j-i);
        tmp = lower(tmp);
        if (count.find(tmp) == count.end())
            count[tmp] = 1;
        else
            count[tmp] += 1;

        i = j;

        while (!alphanumerical(str[i])&&i < str.length())
            i++;
    }

    vector<pair<string, int>> vec(count.begin(), count.end());
    sort(vec.begin(), vec.end(), cmp);

    cout << vec.begin()->first << ' ' << vec.begin()->second;
    return 0;
}

关键点

  • map元素排序

猜你喜欢

转载自blog.csdn.net/Mind_The_Gap/article/details/114067672