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