Codeforce 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 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值