题解 | 宝石手串

宝石手串

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

import java.util.Scanner;


public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        while (n-- > 0) {
            int m = sc.nextInt();
            sc.nextLine();
            String str = sc.nextLine();
            // 模拟循环
            String doubleStr = str + str;
            char[] chars = doubleStr.toCharArray();
            int ans = Integer.MAX_VALUE;
            for (int i = 0; i < chars.length; i++) {
                for (int j = i + 1; j < chars.length; j++) {
                    if (chars[i] == chars[j]) {
                        ans = Math.min(ans, j - i - 1);
                        break;
                    }
                }
            }
            if (ans >= m - 1) {
                // 原本的字符串最远距离应该是m-2
                System.out.println("-1");
            } else {
                System.out.println(ans);
            }
        }

    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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