返回介绍

solution / 1300-1399 / 1374.Generate a String With Characters That Have Odd Counts / README_EN

发布于 2024-06-17 01:03:20 字数 3209 浏览 0 评论 0 收藏 0

1374. Generate a String With Characters That Have Odd Counts

中文文档

Description

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

Solutions

Solution 1: Construction

If $n$ is odd, then we can directly construct a string with $n$ 'a' characters.

If $n$ is even, then we can construct a string with $n-1$ 'a' characters and $1$ 'b' character.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string.

class Solution:
  def generateTheString(self, n: int) -> str:
    return 'a' * n if n & 1 else 'a' * (n - 1) + 'b'
class Solution {
  public String generateTheString(int n) {
    return (n % 2 == 1) ? "a".repeat(n) : "a".repeat(n - 1) + "b";
  }
}
class Solution {
public:
  string generateTheString(int n) {
    string ans(n, 'a');
    if (n % 2 == 0) {
      ans[0] = 'b';
    }
    return ans;
  }
};
func generateTheString(n int) string {
  ans := strings.Repeat("a", n-1)
  if n%2 == 0 {
    ans += "b"
  } else {
    ans += "a"
  }
  return ans
}
function generateTheString(n: number): string {
  const ans = Array(n).fill('a');
  if (n % 2 === 0) {
    ans[0] = 'b';
  }
  return ans.join('');
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文