import sys
T = int(sys.stdin.readline().strip())
for _ in range(T):
n = int(sys.stdin.readline().strip())
string = list(sys.stdin.readline().strip())
# 特殊情况
if n == 2 and string[0] != string[1]:
print(-1)
continue
# 26个字母各自的最小距离(环)
distance = [float('inf') for _ in range(26)]
# 上一个下标
index_pre = [-1 for _ in range(26)]
# 第一个下标
index_first = [-1 for _ in range(26)]
# 遍历
for i in range(n):
chr_ord = ord(string[i]) - 97
# 第一次遇到
if index_pre[chr_ord] == -1:
index_first[chr_ord] = i
else:
#算距离
distance[chr_ord] = min(distance[chr_ord], i - index_pre[chr_ord] - 1, n - i + index_first[chr_ord] - 1)
index_pre[chr_ord] = i
if min(distance) == float('inf'):
print(-1)
else:
print(min(distance))
什么玩意儿让我写半天??



京公网安备 11010502036488号