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 an array A = ["babca","bbazb"] and deletion indices {0, 1, 4}, then the final array after deletions is ["bc","az"].
Suppose we chose a set of deletion indices D such that after deletions, the final array has every element (row) in lexicographic order.
For clarity, A[0] is in lexicographic order (ie. A[0][0] <= A[0][1] <= ... <= A[0][A[0].length - 1]), A[1] is in lexicographic order (ie. A[1][0] <= A[1][1] <= ... <= A[1][A[1].length - 1]), and so on.
Return the minimum possible value of D.length.
Example 1:
Input: ["babca","bbazb"]
Output: 3
Explanation: After deleting columns 0, 1, and 4, the final array is A = ["bc", "az"].
Both these rows are individually in lexicographic order (ie. A[0][0] <= A[0][1] and A[1][0] <= A[1][1]).
Note that A[0] > A[1] - the array A isn't necessarily in lexicographic order.
Example 2:
Input: ["edcba"]
Output: 4
Explanation: If we delete less than 4 columns, the only row won't be lexicographically sorted.
Example 3:
Input: ["ghi","def","abc"]
Output: 0
Explanation: All rows are already lexicographically sorted.
Note:
1 <= A.length <= 100
1 <= A[i].length <= 100
题意:给出一个元素为string类型的数组,每个string长n,字符串每行一个罗下来,每次操作删除某一列,也就是每个string删除相同位置的一个字符,最少要删除多少列使得所有string最终都是字典序。
解法:最终所有字符串都是字典序,也就是每一列的元素字典序都小于对应的后面列的元素,把每一列的字符看作一个元素,就相当于找字符串的最长上升子序列。
class Solution {
public:
int minDeletionSize(vector<string>& A) {
int m = A.size(), n = A[0].size();
int ans = n - 1, k;
vector<int> dp(n, 1);
for(int j = 1; j < n; ++j){//直接按列比较
for(int i = 0; i < j; ++i){
for(k = 0; k < m; ++k){//两列可以比较的前提是,两列中每行的元素对应的字符都满足字典序
if(A[k][i] > A[k][j])
break;
}
if(k == m)//两列所有对应行的元素字典序都是递增的
dp[j] = max(dp[j], dp[i] + 1);
}
ans = min(ans, n - dp[j]);
}
return ans;
}
};