We are given an array A
of N
lowercase letter strings, all of the same length.
Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.
For example, if we have a string "
abcdef
"
and deletion indices {0, 2, 3}
, then the final string after deletion is "
bef
"
.
Suppose we chose a set of deletion indices D
such that after deletions, each remaining column in A is in non-decreasing sorted order.
Formally, the c
-th column is [A[0][c], A[1][c], ..., A[A.length-1][c]]
Return the minimum possible value of D.length
.
Example 1:
Input: ["cba","daf","ghi"] Output: 1
Example 2:
Input: ["a","b"] Output: 0
Example 3:
Input: ["zyx","wvu","tsr"] Output: 3
Note:
1 <= A.length <= 100
1 <= A[i].length <= 1000
给出由
N
个小写字母串组成的数组 A
,所有小写字母串的长度都相同。
现在,我们可以选择任何一组删除索引,对于每个字符串,我们将删除这些索引中的所有字符。
举个例子,如果字符串为 "
abcdef
"
,且删除索引是 {0, 2, 3}
,那么删除之后的最终字符串为 "
bef
"
。
假设我们选择了一组删除索引 D
,在执行删除操作之后,A
中剩余的每一列都是有序的。
形式上,第 c
列为 [A[0][c], A[1][c], ..., A[A.length-1][c]]
返回 D.length
的最小可能值。
示例 1:
输入:["cba","daf","ghi"] 输出:1
示例 2:
输入:["a","b"] 输出:0
示例 3:
输入:["zyx","wvu","tsr"] 输出:3
提示:
1 <= A.length <= 100
1 <= A[i].length <= 1000
超出时间限制
1 class Solution { 2 func minDeletionSize(_ A: [String]) -> Int { 3 var n:Int = A.count 4 var ret:Int = 0 5 outer: 6 for i in 0..<A[0].count 7 { 8 for j in 0..<(n - 1) 9 { 10 if A[j][i] > A[j+1][i] 11 { 12 ret += 1 13 continue outer 14 } 15 } 16 } 17 return ret 18 } 19 } 20 extension String { 21 //subscript函数可以检索数组中的值 22 //直接按照索引方式截取指定索引的字符 23 subscript (_ i: Int) -> Character { 24 //读取字符 25 get {return self[index(startIndex, offsetBy: i)]} 26 } 27 }
原文地址:https://www.cnblogs.com/strengthen/p/9977742.html