B. Two-gram
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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
s
s consisting of
n
n 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
s
s = “BBAABBBA” the answer is two-gram “BB”, which contained in
s
s 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
n
n (
2
≤
n
≤
100
2≤n≤100) — the length of string
s
s. The second line of the input contains the string
s
s consisting of
n
n capital Latin letters.
Output
Print the only line containing exactly two capital Latin letters — any two-gram contained in the given string
s
s as a substring (i.e. two consecutive characters of the string) maximal number of times.
Examples
inputCopy
7
ABACABA
outputCopy
AB
inputCopy
5
ZZZAA
outputCopy
ZZ
Note
In the first example “BA” is also valid answer.
In the second example the only two-gram “ZZ” can be printed because it contained in the string “ZZZAA” two times.
#include <bits/stdc++.h>//c++写上这句话
#include<stdio.h>
#include<string>//注意是string而不是string.h
using namespace std;
int main()
{
string s,str;
int n,i,j,cnt=0,ans;
cin >> n >> s;
for(i=0;i<n-1;i++)
{ ans=0;//因为是两组两组的进行比较,要的是最后的最大值,所以每次都要清零
for(j=i;j<n-1;j++)
{
if(s[j]==s[i]&&s[j+1]==s[i+1])
ans++;
}//第二个for循环就是对第一串两个两个的进行比较,找到相同的就加加
if(ans>cnt)//进行比较之后取最大值
{
cnt=ans;
str.clear();//每次都存入两个数,每次都更新成最新的,所以每次都要清零
str.push_back(s[i]);
str.push_back(s[i+1]);
}
}
cout<<str<<endl;
return 0;
}
题意:让我们从一串字符串中选出出现次数最多的两个连续的字符,并输出;
思路:用两个for循环,进行比较,见代码