LeetCode知识点总结 - 955

给定一个字符串数组,题目要求通过删除某些列使数组在字典序下排列。解决方案是遍历数组,使用布尔数组记录每一列是否已排序,若发现不连续的有序子数组,则增加删除次数。返回最少删除次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode 955. Delete Columns to Make Sorted II

考点难度
GreedyEasy
题目

You are given an array of n strings strs, all of the same length.

We may choose any deletion indices, and we delete all the characters in those indices for each string.

For example, if we have strs = [“abcdef”,“uvwxyz”] and deletion indices {0, 2, 3}, then the final array after deletions is [“bef”, “vyz”].

Suppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= … <= strs[n - 1]). Return the minimum possible value of answer.length.

思路

如果 A[i] < A[i + 1],boolean array sorted[i] = true。对于每一列,如果有unsorted rows就删掉这一列。

答案
class Solution(object):
    def minDeletionSize(self, A):
        res, n, m = 0, len(A), len(A[0])
        is_sorted = [0] * (n - 1)
        for j in range(m):
            is_sorted2 = is_sorted[:]
            for i in range(n - 1):
                if A[i][j] > A[i + 1][j] and is_sorted[i] == 0:
                    res += 1
                    break
                is_sorted2[i] |= A[i][j] < A[i + 1][j]
            else:
                is_sorted = is_sorted2
        return res  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值