Skip to content

Commit e9c6b0a

Browse files
committed
feat: 20260307 check in
1 parent 7947823 commit e9c6b0a

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# 1888. 使二进制字符串字符交替的最少反转次数
2+
3+
> **日期**:2026-03-07
4+
> **所用时间**:10min
5+
> **知识点**:滑动窗口、字符串
6+
7+
## 1. 滑动窗口(循环展开)
8+
9+
交替串只有两种:偶数位为 0、奇数位为 1(0101...),或反之(1010...)。若允许循环左移,等价于在「原串重复两次」上枚举每个长度为 `n` 的起点,计算该段变为 0101... 所需反转次数 `cnt`,另一种模式为 `n - cnt`,取所有窗口的 `min(cnt, n - cnt)` 的最小值即可。
10+
11+
实现:在长度为 `2n - 1` 的虚拟串上滑动窗口(下标 `i` 对应 `s[i % n]`),按 0101 模式统计当前窗口内需反转的个数 `cnt`;窗口左端 `l >= 0` 时用 `min(ans, cnt, n - cnt)` 更新答案,并随窗口右移用当前左端字符是否需反转来更新 `cnt`
12+
13+
复杂度分析:
14+
15+
- 时间复杂度:$O(n)$
16+
- 空间复杂度:$O(1)$
17+
18+
**Python3**
19+
20+
```python
21+
class Solution:
22+
def minFlips(self, s: str) -> int:
23+
ans = n = len(s)
24+
cnt = 0
25+
26+
for i in range(2 * n - 1):
27+
if int(s[i % n]) % 2 != i % 2:
28+
cnt += 1
29+
l = i - n + 1
30+
if l < 0:
31+
continue
32+
ans = min(ans, cnt, n - cnt)
33+
if int(s[l % n]) % 2 != l % 2:
34+
cnt -= 1
35+
return ans
36+
```

0 commit comments

Comments
 (0)