Back to photostream

Generate a String With Characters That Have Odd Counts Leetcode Solution

Problem Statement

In this problem, we are given a length. We have to generate a string that has all characters an odd number of times. For example, aaaaab is a valid string because count(a)=5 and count(b)=1.

But, aaabbc is not a valid string here because count(b)=2 which is an even number.

Example

n = 4

"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".

n = 2

"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".

Approach

We can use a trick here.

If the length of string is odd number then we can use a single character throughout to create the string, and if the input length is even number then we can create a string having just two characters.

One character occuring n-1 times (which will be an odd number because n is even here) and anoter character just once (which is ofcourse an odd count).

 

For example n=4, our output will be aaab

and if n=3, our output will be aaa

 

we are just using characters a and b in our solution, there are more options of characters if you want.

Implementation

C++ Program for Generate a String With Characters That Have Odd Counts Leetcode Solution

#include

using namespace std;

 

string generateTheString(int n)

{

string str;

if(n%2==0)

{

for(int i=0;i

 

www.tutorialcup.com/leetcode-solutions/generate-a-string-...

27 views
0 faves
0 comments
Uploaded on October 20, 2021
Taken on December 25, 2020