[leetcode] 955. Delete Columns to Make Sorted II

Description

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.

Example 1:

Input: strs = ["ca","bb","ac"]
Output: 1
Explanation: 
After deleting the first column, strs = ["a", "b", "c"].
Now strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]).
We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.

Example 2:

Input: strs = ["xc","yb","za"]
Output: 0
Explanation: 
strs is already in lexicographic order, so we do not need to delete anything.
Note that the rows of strs are not necessarily in lexicographic order:
i.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...)

Example 3:

Input: strs = ["zyx","wvu","tsr"]
Output: 3
Explanation: We have to delete every column.

Constraints:

  • n == strs.length
  • 1 <= n <= 100
  • 1 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.

分析

题目的意思是:这道题给定字符串数组,然后删除其中的某些列使得删除后的字符串按照顺序排序,给出最小删除后的序列。

  • 思路很直接,贪心的方法,按照列进行遍历,删除非字典顺序的列,然后剩下的就是排好序的字符串列表了。
  • 这样有一个毛病,就是有些字符串的列的字符是一样的,这就需要看下一列了。我们用order记录一列的当前字符和下一个字符的关系,就容易判断了,如果order是全0,说明找到了符合要求的列,直接返回就行了。
  • 如果不满足字典顺序(当前的字符比下一个字符大),则res更新,跳出循环。
  • 如果满足字典顺序(当前的字符比下一个字符小),还要判断是否严格满足字典顺序(排除当前的字符等于下一个字符的情况)。

主意这里面的for else的用法,for里面执行完之后才会调用else语句,如果for通过break跳出来了,则else不会执行的哈。python挺神奇的操作,哈哈。

代码

class Solution:
    def minDeletionSize(self, strs: List[str]) -> int:
        res=0
        order=[1]*(len(strs)-1)
        m=len(strs)
        n=len(strs[0])
        for j in range(n):
            if(sum(order)==0):
                return res
            for i in range(m-1):
                if(order[i]==0):
                    continue
                if(strs[i][j]>strs[i+1][j]):
                    res+=1
                    break
            else:
                for i in range(m-1):
                    if(strs[i][j]<strs[i+1][j]):
                        order[i]=0
        return res

参考文献

955.Delete Columns to Make Sorted II(删列造序
[LeetCode] 955. Delete Columns to Make Sorted II 删除列使其有序之二

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值