#include <iostream>
#include <mutex>
using namespace std;
int vis[10010];
int solve() {
    int n;
    string s;
    cin >> n >> s;
    if (n == 2 && s[0] != s[1]) {
        return -1;
        // return ;
    }
    // s = "" + s;
    // int len = s.length();
    if (n % 2 == 1) {
        int mx = (n - 3) / 2;
        for (int i = 1; i <= mx+1; i++) {
            for (int j = 0; j < n; j++) {
                if (s[j] == s[(j + i) % n]) {
                    // cout << i - 1 << '\n';
                    return i-1;
                }
            }
        }
    } else {
        int mx = (n - 4) / 2+1;
        for (int i = 1; i <= mx; i++) {
            for (int j = 0; j < n; j++) {
                if (s[j] == s[(j + i) % n]) {
                    // cout << i - 1 << '\n';
                    return i-1;
                }
            }
        }
    }
    return -1;
}
int main() {
    int t;
    cin >> t;
    while (t--) {
        int res = solve();
        cout<<res<<'\n';
    }
}
// 64 位输出请用 printf("%lld")

看了大佬的题解后做的,好像可以转换为找最近相同字符的距离,如果没有相等的只能输出-1.

活动地址https://www.nowcoder.com/discuss/726480854079250432