CodeForces - 977B Two-gram STL

CodeForces - 977B

Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" — three distinct two-grams.

You are given a string ss consisting of nn capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of the string) maximal number of times. For example, for string ss = "BBAABBBA" the answer is two-gram "BB", which contained in ss three times. In other words, find any most frequent two-gram.

Note that occurrences of the two-gram can overlap with each other.

Input

The first line of the input contains integer number nn (2≤n≤1002≤n≤100) — the length of string ss. The second line of the input contains the string ss consisting of nn capital Latin letters.

Output

Print the only line containing exactly two capital Latin letters — any two-gram contained in the given string ss as a substring (i.e. two consecutive characters of the string) maximal number of times.

#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
int main()
{
    int n;
    string s;
    char str[3];

    while(cin>>n>>s)
    {
        map<string,int> m;
        int len=s.length();
        for(int i=0;i<len-1;++i)
        {
            str[0]=s[i];
            str[1]=s[i+1];
            str[2]='\0'; 
            m[str]++;
        }
        map<string,int> :: iterator it;
        int ans=-1<<30;
        for(it=m.begin();it!=m.end();it++)
        {
            if(it->second>ans)
            {
                ans=it->second; 
            }
        } 
        for(it=m.begin();it!=m.end();it++)
        {
            if(it->second==ans)
            {
                cout<<it->first<<endl;
                break; 
            }
        } 
    }
    return 0;
}
Last modification:January 12th, 2020 at 04:34 am
如果觉得我的文章对你有用,请随意赞赏