每个测试文件均包含多组测试数据。第一行输入一个整数
代表数据组数,每组测试数据描述如下:
第一行输入一个整数
代表手串初始的宝石数量。
第二行输入一个长度为
、仅由小写字母构成的字符串,代表手串上每个宝石的属性。
除此之外,保证单个测试文件的
之和不超过
。
对于每一组测试数据,如果手环无法破坏,直接输出
;否则,在一行上输出一个整数,代表手串断开需要的最少操作次数。
2 2 ac 3 aac
-1 0
把原字符串再复制一份,模拟收尾相连的字符串,比如原字符串为ac,我们把它变为acac,
从头开始遍历字符串,用HashMap时刻记录各个元素最近出现的位置,求出距离最小值。
注意,如果遍历结束,距离最小值为字符串的长度 - 1,说明原字符串没有相同元素,返回-1。
否则返回距离的最小值。
import java.util.Scanner;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
for (int i = 0; i < T; i++) {
int n = in.nextInt();
in.nextLine();
String s = in.nextLine();
String str = s + s;
Map<Character, Integer> map = new HashMap<>();
char[] chars = str.toCharArray();
int min = Integer.MAX_VALUE;
for (int j = 0; j < chars.length; j++) {
if (map.containsKey(chars[j])) {
min = Math.min(min, j - map.get(chars[j]) - 1);
}
map.put(chars[j], j);
}
if (min == s.length() - 1) {
System.out.println(-1);
} else {
System.out.println(min);
}
}
}
}