Java 实现构造 01 串包含指定数量的回文子串

问题描述:

给定两个整数 n 和 k,需要构造一个长度为 n 的 01 串,其中恰好包含 k 个长度为 3 的回文子串。回文子串是指正着读和倒着读相同的字符串,例如 '101' 是回文子串,而 '001' 不是。

代码实现:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int k = scanner.nextInt();
        scanner.close();

        StringBuilder sb = new StringBuilder();

        // 构造长度为n的01串
        for (int i = 0; i < n; i++) {
            sb.append(i % 2);
        }

        String s = sb.toString();

        // 计算01串中长度为3的回文子串的个数
        int count = 0;
        for (int i = 0; i <= n - 3; i++) {
            if (isPalindrome(s.substring(i, i + 3))) {
                count++;
            }
        }

        // 如果回文子串的个数等于k,则输出构造的01串;否则输出-1
        if (count == k) {
            System.out.println(s);
        } else {
            System.out.println(-1);
        }
    }

    // 判断一个字符串是否是回文串
    private static boolean isPalindrome(String s) {
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}

代码说明:

  1. 使用 Scanner 类从用户输入获取 n 和 k 的值。
  2. 使用 StringBuilder 类构造长度为 n 的 01 串,其中第 i 位的值为 i % 2。
  3. 遍历 01 串,判断每个长度为 3 的子串是否为回文子串,并统计回文子串的个数。
  4. 如果回文子串的个数等于 k,则输出构造的 01 串;否则输出 -1。

使用方法:

运行该程序,输入 n 和 k 的值,即可得到相应的 01 串作为输出。如果无法构造满足条件的 01 串,则输出 -1。

示例:

输入:5 2
输出:10101
输入:4 3
输出:-1
Java 实现构造 01 串包含指定数量的回文子串

原文地址: https://www.cveoy.top/t/topic/qvFT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录