Skip to content

Commit 073e4f9

Browse files
committed
chore: add daily leetcode post 1653. 使字符串平衡的最少删除次数_translated
1 parent c84490d commit 073e4f9

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
---
2+
title: 1653. The minimum number of times to balance the string balance.md
3+
date: '2024.01.01 0:00'
4+
tags:
5+
- - Python
6+
- - answer
7+
abbrlink: cac21f27
8+
---
9+
10+
# topic:
11+
12+
[1653. The minimum number of times to balance the string balance.md](https://leetcode.cn/problems/minimum-deletions-to-make-string-balanced/description/)
13+
14+
# Thought:
15+
16+
ask:Why if-else Write (c - 'a') * 2 - 1 It will be much faster?
17+
18+
answer:CPU I encounter a branch(Condition jump instruction)Which branch of the code will be predicted when the code is executed,If the prediction is correct,
19+
CPU It will continue to execute the program in accordance with the predicted path。But if the prediction fails,CPU You need to roll back the previous instructions and load the correct instructions,To ensure the correctness of the program execution。
20+
21+
For the data of this question,character ‘a’ and ‘b’ It can be considered to appear random,In this case, the branch prediction will be available 50% Probability failure。
22+
失败导致的回滚and加载操作需要消耗额外的 CPU cycle,If the branch can be removed at a smaller price,The situation of this question can inevitably bring efficiency improvement。
23+
24+
Notice:This optimization method often reduces readability,It's best not to use in business code。
25+
26+
27+
# Code:
28+
29+
```python
30+
class Solution:
31+
def minimumDeletions(self, s: str) -> int:
32+
ans = delete = s.count('a')
33+
for c in s:
34+
delete -= 1 if c == 'a' else -1
35+
if delete < ans: # Manually min It will be much faster
36+
ans = delete
37+
return ans
38+
39+
```

0 commit comments

Comments
 (0)