LeetCode Generate a String With Characters That Have Odd Counts

1374. Generate a String With Characters That Have Odd Counts

Given an integer nreturn 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-1次,外加另一个字符。

完整代码如下:

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

本代码提交AC,用时0MS。

Leave a Reply

Your email address will not be published. Required fields are marked *