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
program main
implicit none
integer :: i, n
character(len=500) :: str
do i = 1, size(examples)
read (examples(i), *) n
call solve(n, str)
write (*, '(A)') trim(str)
end do
contains
subroutine solve(n, str)
implicit none
integer, intent(in) :: n
character(len=*), intent(out) :: str
integer :: i, j
str = ''
do i = 97, 122
do j = 1, mod(n, 2) + 1
str = str // char(i)
end do
end do
end subroutine solve
end program main
character(len=*), parameter :: examples(3) = (/ &
'4', & ! pppz
'2', & ! xy
'7' & ! holasss
/)
temp.f95:1:12: 1 | program main | 1 ...... 35 | /) | 2 Error: Two main PROGRAMs at (1) and (2)
```
program main
implicit none
integer :: n
character(len=500) :: s
read(*,*) n
s = solve(n)
write(*,*) s
contains
function solve(n) result(s)
implicit none
integer, intent(in) :: n
character(len=500) :: s
integer :: i, j
s = ""
do i = 1, n
do j = 1, 26
if (mod(i, j) == 0) then
s = s // char(iachar('a') + j - 1)
end if
end do
end do
end function solve
end program main
```
temp.f95:1:2: 1 | ``` | 1 Error: Invalid character in name at (1) temp.f95:32:2: 32 | ``` | 1 Error: Invalid character in name at (1)
def generateTheString(n: int) -> str:
result = 'a' * n
if n % 2 == 0:
result = result[:-1] + 'b'
return result
The algorithm to solve this problem is straightforward. We initialize the result with a single character (lowercase 'a') repeated n
times. If the given integer n
is even, replace the last character with a different character (lowercase 'b') to make sure that each character occurrence is odd. The resulting string contains each character an odd number of times, satisfying the problem's constraints.
#include <string>
using namespace std;
string generateTheString(int n) {
string result(n, 'a');
if (n % 2 == 0)
result[n - 1] = 'b';
return result;
}
The algorithm to solve this problem is straightforward. We initialize the result with a single character (lowercase 'a') repeated n
times. If the given integer n
is even, replace the last character with a different character (lowercase 'b') to make sure that each character occurrence is odd. The resulting string contains each character an odd number of times, satisfying the problem's constraints.