Skip to content

Commit d98902a

Browse files
NoyeArkcursoragent
andcommitted
feat: 20260220 check in
Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent ecdc9cc commit d98902a

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# [761. 特殊的二进制字符串](https://leetcode.cn/problems/special-binary-string/description/)
2+
3+
> **日期**:2026-02-20
4+
> **所用时间**:5min
5+
> **知识点**:递归、分治
6+
7+
## 1. 题目描述
8+
9+
**特殊的二进制序列**满足以下两个性质:
10+
11+
- 序列中 `0` 的个数与 `1` 的个数相等;
12+
- 序列的**每一个前缀**里,`1` 的个数都**大于等于** `0` 的个数。
13+
14+
你可以进行任意次操作:每次选择字符串中两个**连续且非空**的「特殊子串」,交换它们的位置。请返回经过任意次操作后,能得到的**字典序最大**的字符串。
15+
16+
**示例 1:**
17+
18+
```
19+
输入:s = "11011000"
20+
输出:"11100100"
21+
解释:例如将子串 "10"(下标 1 起)与 "1100"(下标 3 起)交换,得到 "11100100" 等,其中字典序最大的即为答案。
22+
```
23+
24+
**提示:**
25+
26+
- `1 <= s.length <= 50`
27+
- `s` 仅由 `'0'``'1'` 组成
28+
- `s` 是特殊的二进制序列
29+
30+
## 2. 递归分解 + 按字典序排序后拼接
31+
32+
`s` 拆成若干**最小特殊子串**:用差分(遇 `1` 加一、遇 `0` 减一)扫描,当差分再次为 0 时截出一段,形如 `1 + 中间 + 0`,中间部分递归处理得到字典序最大。把所有这样的子串按**字典序从大到小**排序后拼接,即为当前层的最优结果。
33+
34+
复杂度分析:
35+
36+
- **时间复杂度**:$O(n^2)$(递归层数 × 每层排序)。
37+
- **空间复杂度**:$O(n)$(递归栈及临时字符串)。
38+
39+
**Python3**
40+
41+
```python
42+
class Solution:
43+
def makeLargestSpecial(self, s: str) -> str:
44+
if len(s) <= 2:
45+
return s
46+
47+
sub_s = []
48+
diff = 0
49+
st = 0
50+
for i, c in enumerate(s):
51+
if c == '1':
52+
diff += 1
53+
else:
54+
diff -= 1
55+
if diff == 0:
56+
sub_s.append('1' + self.makeLargestSpecial(s[st + 1: i]) + '0')
57+
st = i + 1
58+
59+
sub_s.sort(reverse=True)
60+
return ''.join(sub_s)
61+
```

0 commit comments

Comments
 (0)