A Perfectly Balanced String?(Codeforces Round #785 (Div. 2))

A Perfectly Balanced String?

Let’s call a string s perfectly balanced if for all possible triplets (t,u,v) such that t is a non-empty substring of s and u and v are characters present in s, the difference between the frequencies of u and v in t is not more than 1.

For example, the strings “aba” and “abc” are perfectly balanced but “abb” is not because for the triplet (“bb”,‘a’,‘b’), the condition is not satisfied.

You are given a string s consisting of lowercase English letters only. Your task is to determine whether s is perfectly balanced or not.

A string b is called a substring of another string a if b can be obtained by deleting some characters (possibly 0) from the start and some characters (possibly 0) from the end of a.

Input
The first line of input contains a single integer t (1≤t≤2⋅104) denoting the number of testcases.

Each of the next t lines contain a single string s (1≤|s|≤2⋅105), consisting of lowercase English letters.

It is guaranteed that the sum of |s| over all testcases does not exceed 2⋅105.

Output
For each test case, print “YES” if s is a perfectly balanced string, and “NO” otherwise.

You may print each letter in any case (for example, “YES”, “Yes”, “yes”, “yEs” will all be recognized as positive answer).

Example
input

5
aba
abb
abc
aaaaa
abcba

output
YES
NO
YES
YES
NO

题意: 选取任意不为0的长度的子串,如果子串中出现有这个串中任意两个字母数量的差值>=2,则输出NO,否则输出YES

以下思路来自 这位dalao

思路:

定理: 定义s 中不同字符的个数为k ,长度为n ,如果对于任意的0<=i<n-k+1,长度为k 的子串s [ i , i + k − 1 ]上的字符都是不同的,则s 是平衡的。

必要性: 如果存在子串s [ i , i + k − 1 ] 的字符有相同的,则s 至少有一个字符v没出现在子串s [ i , i + k − 1 ] 上,不妨设s [ i , i + k − 1 ] 的相同字符为u ,则有count ( u ) − count ( v ) > = 2,因此s 是不平衡的。

充分性: 如果对于任意的0 < = i < n − k + 1,长度为k 的子串s [ i , i + k − 1 ] 上的字符都是不同的。对于任意的子串s [ i , i + l − 1 ],它可以拆分成⌈ l / k ⌉段,除了最后一段,每一段上任意字符的出现次数都是1。因此任意字符,在子串s [ i , i + l − 1 ] 的出现次数为⌈ l / k ⌉,或者⌈ l / k ⌉ − 1 ,因此,此时任意字符的在子串s [ i , i + l − 1 ] 的出现次数的差值的绝对值小于等于1。因此,s 是平衡的。

上述定理也可以转化为s 的前k 个字符不同,对于任意i > = k 的字符,要求
s i = = s i − k

AC代码:

#include<bits/stdc++.h>
using namespace std;
string a;
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	int n,i,j,k;
	cin>>n;
	while(n--)
	{
		cin>>a;
		set<char>s;
		for(i=0;i<a.size();i++)//统计不同字符的字串长度
		{
			if(s.find(a[i])==s.end())
			s.insert(a[i]);
			else
			break;
		}
		k=s.size();
		for(i=k;i<a.size();i++)//遍历,如果有不相等的跳出
		{
			if(a[i]!=a[i-k])
			break;
		}
		if(i!=a.size())
		cout<<"NO\n";
		else
		cout<<"YES\n";
	}
	return 0;
 } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值