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 | Input: n = 4 |
Solution
因为题目没有要求字符的使用情况,只是表示需要出现的字符呈现奇数个数。对于构造结果,如果n本身就是奇数个,就输出n个’a’即可,如果n为偶数,输出n-1个’a’以及1个’b’。这样就保证了符合题目要求。
Code
1 | // time: O(n) space:O(n) |