[LeetCode] 1374. Generate a String With Characters That Have Odd Counts 生成每种字符都是奇数个的字符串


Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times.

The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.

Example 1:

Input: n = 4
Output: "pppz"
Explanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love".

Example 2:

Input: n = 2
Output: "xy"
Explanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur".

Example 3:

Input: n = 7
Output: "holasss"

Constraints:

  • 1 <= n <= 500

这道题给了一个整数n,说是返回一个长度为n的字符串,且每个字符的出现次数为奇数。其实这道题返回的字符串可以是很多很多种,并不限制具体使用的字符,只需要满足所有字符出现的次数为奇数即可。那么我们可以尽量少的使用字符,因为给定的整数n可能分为奇偶两种情况,需要分情况讨论一下:当n为奇数的时候,那其实只需要一个字符就可以保证出现次数为奇数了,直接返回长度为n,都是字符a的字符串即可;当n为偶数的时候,那么 n-1 一定是奇数,此时只需要返回一个由 n-1 个字符a组成的字符串,再加上一个字符b即可,参见代码如下:


class Solution {
public:
    string generateTheString(int n) {
        return (n % 2 == 0) ? (string(n - 1, 'a') + "b") : string(n, 'a');
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1374


参考资料:

https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts

https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/solutions/532520/javacpython-one-lines-by-lee215-odk4/

https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/solutions/538947/java-100-speed-and-100-memory-by-riyafa-ei5f/


LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2026-08-26 18:09  Grandyang  阅读(3)  评论(0)    收藏  举报
Fork me on GitHub