LeetCode 1374. Generate a String With Characters That Have Odd Counts

Question

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
2
3
4
5
6
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".

Input: n = 7
Output: "holasss"

Solution

因为题目没有要求字符的使用情况,只是表示需要出现的字符呈现奇数个数。对于构造结果,如果n本身就是奇数个,就输出n个’a’即可,如果n为偶数,输出n-1个’a’以及1个’b’。这样就保证了符合题目要求。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
// time: O(n) space:O(n)
public String generateTheString(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0;i < n - 1; i++) {
sb.append('a');
}
if (n % 2 == 0) {
sb.append('b');
} else {
sb.append('a');
}
return sb.toString();
}