substr 与 substring(CodeForces - 977B Two-gram)

substr 与 substring

         均是截取字符串长度;

均在头文件  <string> 中 包含;

substr(start,length);

start 表示起始的位置,length表示需要的长度

返回为 从 start开始,往后的length个元素,

若不写length 则 从start开始到结束

若length <= 0 则 s.substr(start, length) == NULL;

substring(start,end);

start 表示起始位置,end表示末尾位置

Two - gram:

题目:

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.

题目大意:

给出一个长度为n的字符串,找出其中出现次数最多的连续的两个字符。(包含交叉——AAA 此代表 AA出现两次)

输入

n 和 一个长度为n的字符串

输出

输出出现次数的最多的字符串

样例输入:

Input

7
ABACABA

Output

AB

Input

5
ZZZAA

Output

ZZ

代码

#include <iostream>
#include <string> 
#include <map>
using namespace std;

int main() {
	int n, max = -100;
	string s;
	string maxs;
	cin >> n;
	cin >> s;
	
	map<string, int> m;
	
	for(int i = 0; i < n - 1; i++) {      //0 ~ n-1 因为每次获取的字符串是s[i]s[i+1];
		m[s.substr(i, 2)]++;       //利用map记录此字符串出现的次数
		
		if( m[s.substr(i, 2)] > max) {
			maxs = s.substr(i, 2);        //利用maxs保存出现次数最多的字符串
			max = m[s.substr(i, 2)];   
		}
	}
	
	cout << maxs << endl;
	return 0;
}

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值