题目
给定由 N
个小写字母字符串组成的数组 A
,其中每个字符串长度相等。
选取一个删除索引序列,对于 A
中的每个字符串,删除对应每个索引处的字符。
比如,有 A = ["abcdef", "uvwxyz"]
,删除索引序列 {0, 2, 3}
,删除后 A
为["bef", "vyz"]
。
假设,我们选择了一组删除索引 D
,那么在执行删除操作之后,最终得到的数组的元素是按 字典序(A[0] <= A[1] <= A[2] ... <= A[A.length - 1]
)排列的,然后请你返回 D.length
的最小可能值。
示例 1:
输入:["ca","bb","ac"]
输出:1
解释:
删除第一列后,A = ["a", "b", "c"]。
现在 A 中元素是按字典排列的 (即,A[0] <= A[1] <= A[2])。
我们至少需要进行 1 次删除,因为最初 A 不是按字典序排列的,所以答案是 1。
示例 2:
输入:["xc","yb","za"]
输出:0
解释:
A 的列已经是按字典序排列了,所以我们不需要删除任何东西。
注意 A 的行不需要按字典序排列。
也就是说,A[0][0] <= A[0][1] <= ... 不一定成立。
示例 3:
输入:["zyx","wvu","tsr"]
输出:3
解释:
我们必须删掉每一列。
提示:
1 <= A.length <= 100
1 <= A[i].length <= 100
题解
无官方题解
感想
写了个很慢的。。。
执行用时 : 34 ms, 在Delete Columns to Make Sorted II的Java提交中击败了11.36% 的用户
内存消耗 : 36.8 MB, 在Delete Columns to Make Sorted II的Java提交中击败了100.00% 的用户
class Solution {
public int minDeletionSize(String[] A) {
boolean[] B = new boolean[A[0].length()];
return minDSSub(A, B, 0, 0, A.length);
}
private int minDSSub(String[] A, boolean[] B, int col, int rowFrom, int rowTo) {
System.out.println("现在计算的是minDSSub(A,B,"+col+","+rowFrom+","+rowTo+")");
if (col >= A[0].length()) return 0;
if(B[col]==true) return minDSSub(A,B,col+1,rowFrom,rowTo);
int count = 0;
int from = -1;
for (int i = rowFrom + 1; i < rowTo; i++) {
if (A[i].charAt(col) - A[i - 1].charAt(col) < 0) {
count++;
B[col] = true;
count += minDSSub(A, B, col + 1, rowFrom, rowTo);
break;
} else if (A[i].charAt(col) == A[i - 1].charAt(col)) {
if (from == -1) from = i - 1;
if(i==rowTo-1) {
count+=minDSSub(A,B,col+1,from, rowTo);
from = -1;
}
} else if (from != -1) {
count += minDSSub(A, B, col + 1, from, i);
from = -1;
}
}
return count;
}
}
后来在评论区看到一个思路一样的,只是利用一个数组存储确定排列的行,就可以免去递归函数,从而达到5ms的速度:
执行用时 : 5 ms, 在Delete Columns to Make Sorted II的Java提交中击败了65.91% 的用户
内存消耗 : 37.2 MB, 在Delete Columns to Make Sorted II的Java提交中击败了93.33% 的用户
class Solution {
public static int minDeletionSize(String[] strs){
if (strs == null || strs.length < 2) {
return 0;
}
int arrLen = strs.length;
int strLen = strs[0].length();
// 如果cuts[i] = true, 那么我们不需要再检查 strs[i][j] > strs[i+1][j]
boolean[] cuts = new boolean[arrLen];
int ans = 0;
boolean delete;
for (int j = 0; j < strLen; j++) {
delete = false;
for (int i = 0; i < arrLen - 1; i++) {
if (!cuts[i] && strs[i].charAt(j) > strs[i + 1].charAt(j)) {
ans++;
delete = true;
break;
}
}
if (!delete) {
// 更新cuts
for (int i = 0; i < arrLen - 1; i++) {
if (strs[i].charAt(j) < strs[i + 1].charAt(j)) {
cuts[i] = true;
}
}
}
}
return ans;
}
}