leetcode 1374. Generate a String With Characters That Have Odd Counts(python)

496 阅读1分钟

描述

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"

Note:

1 <= n <= 500

解析

根据题意,只需要判断 n 为奇数的时候,则任取一个小写字母重复 n 次即可。n 为偶数的时候,只需任选两个字母,一个字母重复 1 次,另一个字母重复 (n-1) 次即可。

解答

class Solution(object):
    def generateTheString(self, n):
        """
        :type n: int
        :rtype: str
        """
        if n%2:
            return "a"*n
        return "a"*(n-1)+"b"
        	      
		

运行结果

Runtime: 12 ms, faster than 95.89% of Python online submissions for Generate a String With Characters That Have Odd Counts.
Memory Usage: 13.3 MB, less than 62.56% of Python online submissions for Generate a String With Characters That Have Odd Counts.

原题链接:leetcode.com/problems/ge…