最长好串(原创)

题目及要求

顺串所有字符均是按字典顺序从小到大排列且不含有重复字符

像“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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值