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

Fatboy Slim
2 min readApr 26, 2020

--

Environment: Python 3.7

Key technique: append.

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"

Analysis:

  1. If n is even, add “a” to n-1 location and add “b” in last location.
  2. if n is odd , add “a” in all location.

Solution:

class Solution:
def generateTheString(self, n):
ans=[]
if n%2==0:
for i in range(n-1):
ans.append('a')
ans.append('b')
else:
for i in range(n):
ans.append('a')
return ans

Improved Solution:

class Solution:
def generateTheString(self, n):
ans=[]
if n%2==0:
ans=['a' for i in range(n-1)]
ans.append('b')
else:
ans=['a' for i in range(n)]
return ans

Submission:

Improved Submission:

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet