String 1374. Generate a String With Characters That Have Odd Counts ¶ Time: $O(n)$ Space: $O(n)$ C++JavaPython 1 2 3 4 5 6 7 8 9class Solution { public: string generateTheString(int n) { string s(n, 'a'); if (n % 2 == 0) s.back() = 'b'; return s; } }; 1 2 3 4 5 6 7 8 9 10class Solution { public String generateTheString(int n) { StringBuilder sb = new StringBuilder(n); for (int i = 0; i < n; ++i) sb.append('a'); if (n % 2 == 0) sb.setCharAt(n - 1, 'b'); return sb.toString(); } } 1 2 3 4 5 6class Solution: def generateTheString(self, n: int) -> str: s = 'a' * n if n % 2 == 0: s = s[:-1] + 'b' return s