LeetCode 题解工作台

最大二进制奇数

给你一个 二进制 字符串 s ,其中至少包含一个 '1' 。 你必须按某种方式 重新排列 字符串中的位,使得到的二进制数字是可以由该组合生成的 最大二进制奇数 。 以字符串形式,表示并返回可以由给定组合生成的最大二进制奇数。 注意 返回的结果字符串 可以 含前导零。 示例 1: 输入: s = "0…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 贪心·invariant

bolt

答案摘要

我们先统计字符串 中 的个数,记为 。那么我们将 $cnt - 1$ 个 放在最高位,剩下的 $|s| - cnt$ 个 放在后面,最后再加上一个 即可。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 二进制 字符串 s ,其中至少包含一个 '1'

你必须按某种方式 重新排列 字符串中的位,使得到的二进制数字是可以由该组合生成的 最大二进制奇数

以字符串形式,表示并返回可以由给定组合生成的最大二进制奇数。

注意 返回的结果字符串 可以 含前导零。

 

示例 1:

输入:s = "010"
输出:"001"
解释:因为字符串 s 中仅有一个 '1' ,其必须出现在最后一位上。所以答案是 "001" 。

示例 2:

输入:s = "0101"
输出:"1001"
解释:其中一个 '1' 必须出现在最后一位上。而由剩下的数字可以生产的最大数字是 "100" 。所以答案是 "1001" 。

 

提示:

  • 1 <= s.length <= 100
  • s 仅由 '0''1' 组成
  • s 中至少包含一个 '1'
lightbulb

解题思路

方法一:贪心

我们先统计字符串 ss11 的个数,记为 cntcnt。那么我们将 cnt1cnt - 111 放在最高位,剩下的 scnt|s| - cnt00 放在后面,最后再加上一个 11 即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为字符串 ss 的长度。

1
2
3
4
5
class Solution:
    def maximumOddBinaryNumber(self, s: str) -> str:
        cnt = s.count("1")
        return "1" * (cnt - 1) + (len(s) - cnt) * "0" + "1"
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Ask why placing a '1' at the end guarantees an odd number.

  • question_mark

    Check if candidates correctly separate the last '1' from the remaining bits.

  • question_mark

    Expect explanation of greedy choice for maximizing the binary value.

warning

常见陷阱

外企场景
  • error

    Forgetting to reserve one '1' at the least significant position, producing an even number.

  • error

    Reordering '0's and '1's incorrectly, reducing the maximum value.

  • error

    Assuming multiple '1's can occupy the last position, violating the odd constraint.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find the maximum even binary number by placing '0' at the least significant bit.

  • arrow_right_alt

    Count the number of maximum odd binary numbers possible from the same string.

  • arrow_right_alt

    Extend the problem to ternary strings with a similar odd-value constraint.

help

常见问题

外企场景

最大二进制奇数题解:贪心·invariant | LeetCode #2864 简单