[leetcode] 955. Delete Columns to Make Sorted II

网友投稿 663 2022-11-08

[leetcode] 955. Delete Columns to Make Sorted II

[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: 1Explanation: 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: 0Explanation: 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: 3Explanation: We have to delete every column.

Constraints:

n == strs.length1 <= n <= 1001 <= strs[i].length <= 100strs[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]

参考文献

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 213. House Robber II
下一篇:[leetcode] 1558. Minimum Numbers of Function Calls to Make Target Array
相关文章

 发表评论

暂时没有评论,来抢沙发吧~