题目及要求
顺串指所有字符均是按字典顺序从小到大排列,且不含有重复字符
像“abc",“efghijk”,"opqrst"等均为顺串。
异位词 指由相同字母重排列形成的字符串(包括相同的字符串)
像"abs"与"sba"即为异位词。
每个字符串都含有多个异位词(单字符字符串除外),如果一个字符串a的异位词中有一个为顺串,则称这个字符串a为好串。
比如说,"fcdebga"为好串。
给定一个字符串 s ,请你找出其中为好串的最长子串的长度。
输入要求
输入一个整数num(1<=num<=100)表示测试用例个数,每个测试用例包含一个整数n和n行字符串。
每个测试用例如下:
输入一个整数n表示字符串个数(1<=n<=2e5)
接下来输入n行字符串,每一行字符串长度len(1<=len<=100)
输出要求
每两个测试用例之间不用空格空行,每一个字符串对应输出一个整数,表示这个字符串中最长好串的长度。
测试示例
示例一:
输入:
1
3
acyuike
xyz
uybxz
输出:
1
3
2
示例二:
输入:
2
5
acdfbpmnqlkozvwx
aefghjikhjkpo
abbcdefghijklmm
abbcdefgghijklmm
bcdafghejikmlnpoqtsruwvyxz
1
2
输出:
7
7
12
7
26
1
代码
#include "bits/stdc++.h"
using namespace std;
//#define int long long
void solve(int T) {
int n;
cin >> n;
for (int k = 0; k < n; k++) {
string s;
cin >> s;
int left = 0, right = 0, max = 0, len;
unordered_set<char> hash;
vector<int> count(26);
map<int, int> hashtable;
while (left <= right && right < s.size()) {
while (left <= right && hash.count(s.at(right)) == 1) {
hash.erase(hash.find(s.at(left)));
hashtable.erase(s.at(left) - 'a');
count.at(s.at(left) - 'a') = 0;
left++;
}
while (right < s.size() && left <= right && !hash.count(s.at(right))) {
hash.emplace(s.at(right));
hashtable[s.at(right) - 'a'] = right;
count.at(s.at(right) - 'a')++;
right++;
}
len = 0;
int i = 0, sta, end;
while (i < 26) {
while (i < 26 && !count.at(i))
i++;
sta = i;
while (i < 26 && count.at(i))
i++;
end = i;
set<int> tmp;
for (int j = sta; j < end; j++) {
tmp.insert(hashtable[j]);
}
bool flag = 0;
for (auto item = tmp.begin(); item != tmp.end(); item++) {
++item;
if (item != tmp.end())
if (*item != *(--item) + 1) {
flag = 1;
break;
} else;
else --item;
}
if (!flag)
len = tmp.size();
max = max > len ? max : len;
}
}
cout << max << endl;
}
cout<<endl;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int num, ans;
cin >> num;
for (int i = 0; i < num; i++)
solve(i);
return 0;
}