Codeforces C. Good String

Let’s call left cyclic shift of some string t1t2t3…tn−1tn as string t2t3…tn−1tnt1.

Analogically, let’s call right cyclic shift of string t as string tnt1t2t3…tn−1.

Let’s say string t is good if its left cyclic shift is equal to its right cyclic shift.

You are given string s which consists of digits 0–9.

What is the minimum number of characters you need to erase from s to make it good?

Input
The first line contains single integer t (1≤t≤1000) — the number of test cases.

Next t lines contains test cases — one per line. The first and only line of each test case contains string s (2≤|s|≤2⋅105). Each character si is digit 0–9.

It’s guaranteed that the total length of strings doesn’t exceed 2⋅105.

Output
For each test case, print the minimum number of characters you need to erase from s to make it good.

Example
input
3
95831
100120013
252525252525
output
3
5
0
Note
In the first test case, you can erase any 3 characters, for example, the 1-st, the 3-rd, and the 4-th. You’ll get string 51 and it is good.

In the second test case, we can erase all characters except 0: the remaining string is 0000 and it’s good.

In the third test case, the given string s is already good.

题意:给定一个字符串 t1t2t3t4t5…tn ,问:最少删除几个字符可以使字符串满足 t2t3t4t5…tnt1 = tnt1t2t3t4…tn-1。

思路:只有当字符串转换成 ababababab…(偶数个) 或者 aaaaaa… 这两种形式是满足上述等式,即通过删除只保留单字符或者双字符。单字符好说,直接求得s中每个字符出现的次数即可。对于双字符由于数据范围不大,因此我们可以选择枚举双字符,即从00~99 进行模拟即可。

#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
	//这个题的目的就是使字符串s变成 ababababab.... 或者 aaaaaa... 的形式 至少删去多少个字符 
	int t,l,r,maxx;
	string s;
	cin>>t;
	while(t--)
	{
		map<char,int> m;
		maxx=-1;
		cin>>s;
		for(int i=0;i<s.length();i++)
			m[s[i]]++;
		for(int a=0;a<=9;a++) //由于只能保留 单字符或者双字符,因此对于保留双字符我们枚举从 00~99 
		{
			for(int b=0;b<=9;b++)
			{
				int flag=0,x=0;
				for(int i=0;i<s.length();i++)
				{
					if(s[i]-'0'==a&&flag==0) //这两个if语句是为了 获取一个a后再获取b再获取a再获取b..... 
					{
						flag=1;
						x++;	
					}
					else if(s[i]-'0'==b&&flag==1)
					{
						flag=0;
						x++;	
					}	
				}
				if(x%2==1) //如果最后为奇数,则必须减掉一个 
					x--;
				maxx=max(x,maxx); 
			}
		}
		int maxx1=-1; 
		for(int i=0;i<s.length();i++)  //对于保留单字符,只需要比较m[s[i]] 即可 
		{
			maxx1=max(maxx1,m[s[i]]);
		}
		cout<<min(s.length()-maxx,s.length()-maxx1)<<endl;;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

henulmh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值