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