题解 | 宝石手串
宝石手串
https://www.nowcoder.com/practice/9648c918da794be28575dd121efa1c50
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <climits>
using namespace std;
int main() {
int T;
cin >> T;
while (T--) {
int n;
string s;
cin >> n >> s;
bool found_adjacent = false;
for (int i = 0; i < n; i++) {
if (s[i] == s[(i + 1) % n]) {
found_adjacent = true;
break;
}
}
if (found_adjacent) {
cout << 0 << endl;
continue;
}
vector<int> char_count(26, 0);
for (char c : s) {
char_count[c - 'a']++;
}
bool all_unique = true;
for (int count : char_count) {
if (count > 1) {
all_unique = false;
break;
}
}
if (all_unique) {
cout << -1 << endl;
continue;
}
vector<vector<int>> positions(26);
for (int i = 0; i < n; i++) {
positions[s[i] - 'a'].push_back(i);
}
int min_gap = INT_MAX;
for (int i = 0; i < 26; i++) {
int k = positions[i].size();
if (k <= 1) continue;
sort(positions[i].begin(), positions[i].end());
for (int j = 0; j < k; j++) {
int gap;
if (j < k - 1) {
gap = positions[i][j + 1] - positions[i][j] - 1;
} else {
gap = positions[i][0] + n - positions[i][j] - 1;
}
if (gap < min_gap) {
min_gap = gap;
}
}
}
cout << min_gap << endl;
}
return 0;
}

