Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

生成每种字符都是奇数个的字符串 #147

Open
yankewei opened this issue Aug 1, 2022 · 1 comment
Open

生成每种字符都是奇数个的字符串 #147

yankewei opened this issue Aug 1, 2022 · 1 comment
Labels
字符串 题目类型为字符串 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

yankewei commented Aug 1, 2022

给你一个整数 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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/generate-a-string-with-characters-that-have-odd-counts
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 简单 题目难度为简单 字符串 题目类型为字符串 labels Aug 1, 2022
@yankewei
Copy link
Owner Author

yankewei commented Aug 1, 2022

只用 a 和 b 两个字符串即可,

  • n 是偶数,则使用 n-1 个 a 加上一个 b
  • n 是奇数,则使用 n 个 a
class Solution {

    /**
     * @param Integer $n
     * @return String
     */
    function generateTheString($n) {
        if ($n % 2 === 0) {
            return str_repeat('a', $n-1) . 'b';
        }

        return str_repeat('a', $n);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
字符串 题目类型为字符串 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant