ICPC Greater New York Region 2020 L Evenly Separated Strings

6 篇文章 0 订阅
2 篇文章 0 订阅

L Evenly Separated Strings

题目描述

Given a string consisting of lowercase letters. We say the string is evenly separated if and only if there is an even number of characters between every pair of the same characters. For example, abba is evenly separated while aabba is not. For this problem, you will write a program to determine whether the given string s is evenly separated or not.

输入描述:

Input consists of a single line containing the string of at most 1,000,000 lower-case letters to check if it is evenly separated.

输出描述:

The output line consists of the word YES if the string is evenly separated or NO if the string is not evenly separated.

示例1
输入

abba

输出

YES

示例2
输入

aabba

输出

NO

示例3
输入

abcdefyzfedcba

输出

YES

题目大意:

如果一个字符串的任意两个相同字符之间都隔了偶数个字符,就说明这个字符串是均匀分割的。

给定一个字符串,判断这个字符串是否是均匀分割的。

题解:

通过简单的分析我们发现,假设有三个相同的字符a1、a2和a3,如果a1和a2之间隔了偶数个字符,a2和a3之间也隔了偶数个字符,那么a1和a3之间就必定隔了奇数个字符,不符合要求。所以任意满足要求的字符串中相同的字符最多出现两次。这样我们只要遍历整个字符串,用map记录每个字符的下标,如果相同的字符在前面已经出现过就计算一下相隔的字符数是奇数还是偶数。可以用另外一个map来记录每个字符出现的次数,如果相同字符出现超过两次则直接输出NO。

字符的下标记录可以从1开始,避免map里的初始值0和字符串下标0混淆。

AC代码:

#include <iostream>
#include <map>
using namespace std;
typedef long long ll;
int main() {
    ios::sync_with_stdio(false);
	string s;
	cin >> s;
	map<char, ll> mp, sum; // mp记录字符下标,sum记录字符出现次数 
	for (ll i = 0; i < s.length(); i ++) {
		sum[s[i]] ++;
		if (mp[s[i]] == 0) mp[s[i]] = i + 1; // 字符首次出现记录下标,下标从1开始避免混淆。 
		else {
			ll t = (i - mp[s[i]]) % 2; // t为相隔字符数 
			if (t == 1 || sum[s[i]] > 2) { // 相隔字符数为奇数或相同字符超过2个都不满足 
				cout << "NO\n";
				return 0;
			}
			mp[s[i]] = i + 1; // 更新字符的下标 
		}
	}
	cout << "YES\n";
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值