Given an integer
The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.
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: "aaab"
Approach
Java
public class CharHaveOddCounts {public static void main(String[] args) {int n = 4;System.out.println(generateTheString(n));}static String generateTheString(int n) {String res = "";if (n % 2 != 0) {for (int i = 0; i < n; i++)res += "a";} else {for (int i = 0; i < n - 1; i++)res += "a";res += "b";}return res;}}
C++
#include <bits/stdc++.h>using namespace std;string generateTheString(int n){string res = "";if (n & 1){for (int i = 0; i < n; i++)res += "a";}else{for (int i = 0; i < n - 1; i++)res += "a";res += "b";}return res;}int main(){int n = 4;cout << generateTheString(n);return 0;}
No comments:
Post a Comment