LeetCode 题解工作台
生成每种字符都是奇数个的字符串
给你一个整数 n ,请你返回一个含 n 个字符的字符串,其中每种字符在该字符串中都恰好出现 奇数次 。 返回的字符串必须只含小写英文字母。如果存在多个满足题目要求的字符串,则返回其中任意一个即可。 示例 1: 输入: n = 4 输出: "pppz" 解释: "pppz" 是一个满足题目要求的字符串…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
如果 为奇数,那么直接构造 个 `'a'` 即可。 如果 为偶数,那么构造 个 `'a'` 和 个 `'b'` 即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个整数 n,请你返回一个含 n 个字符的字符串,其中每种字符在该字符串中都恰好出现 奇数次 。
返回的字符串必须只含小写英文字母。如果存在多个满足题目要求的字符串,则返回其中任意一个即可。
示例 1:
输入:n = 4 输出:"pppz" 解释:"pppz" 是一个满足题目要求的字符串,因为 'p' 出现 3 次,且 'z' 出现 1 次。当然,还有很多其他字符串也满足题目要求,比如:"ohhh" 和 "love"。
示例 2:
输入:n = 2 输出:"xy" 解释:"xy" 是一个满足题目要求的字符串,因为 'x' 和 'y' 各出现 1 次。当然,还有很多其他字符串也满足题目要求,比如:"ag" 和 "ur"。
示例 3:
输入:n = 7 输出:"holasss"
提示:
1 <= n <= 500
解题思路
方法一:构造
如果 为奇数,那么直接构造 个 'a' 即可。
如果 为偶数,那么构造 个 'a' 和 个 'b' 即可。
时间复杂度 ,空间复杂度 。其中 为字符串长度。
class Solution:
def generateTheString(self, n: int) -> str:
return 'a' * n if n & 1 else 'a' * (n - 1) + 'b'
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates understanding of string manipulation patterns.
- question_mark
Candidate recognizes that the problem requires efficient handling of odd counts in string construction.
- question_mark
Candidate can adapt the solution for various input sizes, particularly edge cases.
常见陷阱
外企场景- error
Failing to account for n = 1 and constructing the string incorrectly for small values.
- error
Confusing the need for odd counts with simply returning any random string of length n.
- error
Not recognizing the efficiency of directly constructing the string with specific characters ('a' and 'b').
进阶变体
外企场景- arrow_right_alt
Modify the problem to use uppercase letters instead of lowercase.
- arrow_right_alt
Change the problem to require multiple different characters with odd counts.
- arrow_right_alt
Allow characters other than 'a' and 'b' to be used to satisfy the condition.