1374. 生成每种字符都是奇数个的字符串『简单』

题目来源于力扣(LeetCode

一、题目

1374. 生成每种字符都是奇数个的字符串

提示:

1 <= n <= 500

二、解题思路

2.1 数组方式

  1. n 为奇数时,创建长度为 3 的数组,存储三项都为奇数且相加等于 n 的数字

  2. n 为偶数时,创建长度为 2 的数组,存储两个都为奇数且相加等于 n 的数字

  3. 遍历数组,对数组中的元素,即不同字符出现的个数 append 到 StringBuilder 中

  4. 返回字符串

2.2 数组方式改进版

  1. 创建长度为 n 的字符数组,循环往字符数组中赋值 字母字符(同一个)

  2. 判断 n 是否为奇数,为奇数则直接返回字符数组的字符串形式(奇数个的字符,满足要求)

  3. n 为偶数时,将数组首位替换为其他的任一字符,返回数组的字符串形式

三、代码实现

3.1 数组方式

public static String generateTheString(int n) {
    // n == 1 时的特殊情况
    if (n == 1) {
        return "a";
    }
    int[] res;
    // 为奇数时,需要最少三个字母
    if (n % 2 == 1) {
        res = new int[3];
        int j = n % 2;
        res[0] = j;  // 除2取余,余数必为奇数
        res[1] = 1;
        res[2] = (n - j - 1);
    }
    // 为偶数时,需要最少两个字母
    else {
        res = new int[2];
        res[0] = 1;
        res[1] = n - 1;   // 偶数减 1 得到奇数
    }
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < res.length; i++) {
        // 遍历往字符串中添加字符
        while (res[i] > 0) {
            // 从 a 开始,依次往后加 + i,即 i
            sb.append((char) (i + 'a'));
            res[i] --;
        }
    }
    return sb.toString();
}

3.2 数组方式改进版

public static String generateTheString(int n) {
    char[] res = new char[n];
    // n 为奇数时全为字符 ‘a’
    for (int i = 0; i < res.length; i++) {
        res[i] = 'a';
    }
    // n 为偶数时修改数组首位为字符 ‘b’
    if (n % 2 == 0) {
        res[0] = 'b';
    }
    return String.valueOf(res);
}

四、执行用时

4.1 数组方式

4.2 数组方式改进版

五、部分测试用例

public static void main(String[] args) {
    int n = 4;  // output:"pppz"
//    int n = 2;  // output:"xy"
//    int n = 7;  // output:"holasss"
    String result = generateTheString(n);
    System.out.println(result);
}
原文地址:https://www.cnblogs.com/zhiyin1209/p/12879088.html