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 consisting of 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 = “BBAABBBA” the answer is two-gram “BB”, which contained in 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 (2 <= n <= 100) — the length of string s. The second line of the input contains the string s consisting of n capital Latin letters.
Output Print the only line containing exactly two capital Latin letters — any two-gram contained in the given string s as a substring (i.e. two consecutive characters of the string) maximal number of times.
SampleInput 1 7 ABACABA SampleOutput 1 AB SampleInput 2 5 ZZZAA SampleOutput 2 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.
题意:求字符串中出现次数最多两个相邻的字符(相邻不是指字典序中的关系,是单纯数组中(i,i+1)或者(i-1,i)) 思路: 看到题目中n的数据范围小最多只有100 基本上随便写了 水题一道, 不过在这挂一种O(nn)和O(nn*n)的算法 下面献上我的low b代码
#include <iostream> #include <cstring> using namespace std; char s[105]; int main() { int n; while(cin>>n) { cin>>s; int maxi=0; char c,d; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { int cnt=0; for(int k=0;k<n;k++) { if(s[i]==s[k]&&s[j]==s[k+1]) cnt++; } if(cnt>maxi) { c=s[i]; d=s[j]; maxi=cnt; } } } cout<<c<<d<<endl; } }这边简单说一下下面这种方法 就是通过二维数组建立起所有两个相邻的字符与其出现的次数的关系 然后跑一遍标记数组找到最大次数即可 复杂度O(n*n)
#include<iostream> #include <cstdio> using namespace std; char s[105]; int b[205][205]; int main() { int n; cin >> n >> s; for(int i=1;i<n;i++) b[s[i-1]][s[i]]++;///利用二维数组建立关系 int maxi=0; int posi,posj; for(int i='A';i<='Z';i++) { for(int j='A';j<='Z';j++) { if(b[i][j]>maxi) { maxi=b[i][j]; posi=i; posj=j; } } } printf("%c%c",posi,posj); return 0; }