题解 | 宝石手串

宝石手串

https://www.nowcoder.com/practice/9648c918da794be28575dd121efa1c50

#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
    int a;
    cin >> a;
    while (a--) {
        string str;
        int num;
        unordered_map<char, vector<int>> record;
        cin >> num;
        cin >> str;
        if (num == 2) {
            cout << -1 << endl;
        } else {
            int res = num;
            for (int i = 0; i < num; i++) {
                if (record.count(str[i])) {
                    // cout << record[str[i]].back() << " " <<record[str[i]].front() <<endl;
                    res = min({res, i - record[str[i]].back() - 1, num - 1 - i + record[str[i]].front()});

                }
                if (record[str[i]].size() == 2) {
                    record[str[i]][1] = i;
                } else {
                    record[str[i]].push_back(i);
                }
            }
            if (res == num) {
                cout << -1 << endl;
            } else {
                cout << res << endl;
            }
        }
    }


}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

迷茫的大四🐶:自信一点,我认为你可以拿到50k,低于50k完全配不上你的能力,兄弟,不要被他们骗了,你可以的
点赞 评论 收藏
分享
每晚夜里独自颤抖:这个在牛客不是老熟人了吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务