52 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個a
如果n爲偶數,則返回一個a+n-1個b

解答

class Solution {
    public String generateTheString(int n) {
        if(n%2 == 1){
            return "n".repeat(n);
        }
        else{
            return "n".repeat(n-1)+"a";
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章