PAT Grade A Zhenti 1071 Speech Patterns [String Processing] Solution

table of Contents

1. Title

Different
people may have different degrees of preference for synonyms that describe the same thing.

For example, when talking about the police, some people like to use the police and some people like to use the cops.

Analyzing the way you speak helps determine the identity of the speaker, which is very useful for verifying whether the person you are chatting with is the same person.

Now, given a piece of text extracted from someone’s speech, can you determine his most common words?

Input format
Input one line, including a character string, and terminate with carriage return \n.
The output format is
one line, outputting the most frequently used words and their appearance times.

If there are multiple commonly used words, the word with the smallest lexicographic order is output.

Note that when outputting words, they must be all lowercase.

A word refers to a continuous sequence composed of consecutive letters and numbers, separated by non-alphanumeric characters or line beginning/end.

Words are not case sensitive.
Data range The
input string length does not exceed 1048576 and contains at least one uppercase and lowercase letter or number.
Input sample:
Can1: "Can a can can a can? It can!"
Output sample:
can 5

2. Code

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<unordered_map>
using namespace std;
bool check(char c)  //检验字符的合法性
{
    
    
    if(c>='0'&&c<='9') return true;
    if(c>='a'&&c<='z') return true;
    if(c>='A'&&c<='Z') return true;
    return false;
}
char to_lower(char c) //大写的字符转换成小写的
{
    
    
    if (c>='A'&&c<='Z')  c+=32;
    return c;
}
int main()
{
    
    
    string str;
    getline(cin,str);  //读取一行
    unordered_map<string,int>hash;   //建立映射
    for(int i=0;i<str.size();i++)
    {
    
    
        int j=i;      //双指针算法
        if(check(str[i]))
        {
    
    
            string word;
            while(j<str.size()&&check(str[j]))
            {
    
    
                word+=to_lower(str[j]);
                j++;
            }
            i=j;
            hash[word]++;
        }
    }
    string word;
    int cnt=-1;
    for(auto c: hash)
    {
    
    
       if(c.second>cnt||c.second==cnt&&c.first<word)
       {
    
    
           word=c.first;
           cnt=c.second;
       }
    }
    cout<<word<<' '<<cnt<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45629285/article/details/109496625