Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 55d1fc1

Browse files
🐱(greedy): 955. 删列造序 II
1 parent 7893d54 commit 55d1fc1

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

‎docs/algorithm/greedy/README.md‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,3 +228,89 @@ class Solution(object):
228228

229229
return res
230230
```
231+
232+
## 955. 删列造序 II
233+
234+
[原题链接](https://leetcode-cn.com/problems/delete-columns-to-make-sorted-ii/)
235+
236+
### 思路
237+
238+
逐个比较两个相邻字符串的每个字符。假设相邻的两个字符串是 `s1``s2`,参与对比的两个字符分别为 `c1``c2`,这两个字符的对比无非就三种情况:
239+
240+
1. `c1 < c2`,是字典序:此时 `s1``s2` 符合字典序要求,我们无需再比对之后的字符串了
241+
2. `c1 > c2`,非字典序:此时 `s1``s2` 不符合字典序的要求,该索引为必须要删除的索引。如果该索引还没有被删除(也有可能在其他比较的过程中删除了),我们就把这个要删除的索引记录下来,并且把要求的结果 `D.length + 1`,并且从头开始比对所有字符串
242+
3. `c1 == c2`:这种情况比较特殊,看似是字典序,但这两个字符后其他字符的情况将决定 `s1``s2` 是否为字序。因此遇到两个字符相等的情况时,我们依然要继续比对字符串之后的其他字符
243+
244+
### 实现
245+
246+
```python
247+
class Solution(object):
248+
def minDeletionSize(self, A):
249+
"""
250+
:type A: List[str]
251+
:rtype: int
252+
"""
253+
res = 0
254+
a_length = len(A)
255+
s_length = len(A[0])
256+
if a_length == 1:
257+
return 0
258+
259+
# 记录已经删除的列
260+
mark = [0 for _ in range(s_length)]
261+
262+
i = 1
263+
while i < a_length:
264+
pre_a = A[i - 1]
265+
cur_a = A[i]
266+
for j in range(s_length):
267+
# 如果是非字典序且该列还没有删除
268+
if pre_a[j] > cur_a[j] and mark[j] == 0:
269+
mark[j] = 1
270+
res += 1
271+
# 重制 i 的位置,从第一个字符串开始重新比较
272+
i = 0
273+
# 如果该列相等或该列已删除
274+
if pre_a[j] == cur_a[j] or mark[j] == 1:
275+
continue
276+
break
277+
i += 1
278+
279+
return res
280+
```
281+
282+
```swift
283+
class Solution {
284+
func minDeletionSize(_ A: [String]) -> Int {
285+
var res = 0
286+
var aLength = A.count
287+
var sLength = A[0].count
288+
if aLength == 1 {
289+
return 0
290+
}
291+
292+
var mark = [Int](repeating: 0, count: sLength)
293+
294+
var i = 1
295+
while i < aLength {
296+
var preA = Array(A[i - 1])
297+
var curA = Array(A[i])
298+
for j in 0...sLength-1 {
299+
if preA[j] > curA[j] && mark[j] == 0 {
300+
res += 1
301+
mark[j] = 1
302+
i = 0
303+
}
304+
305+
if preA[j] == curA[j] || mark[j] == 1 {
306+
continue
307+
}
308+
309+
break
310+
}
311+
i += 1
312+
}
313+
return res
314+
}
315+
}
316+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /