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 = ["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 D
such that after deletions, the final array has its elements in lexicographic order (A[0] <= A[1] <= A[2] ... <= A[A.length - 1]
).
Return the minimum possible value of D.length
.
Example 1:
Input: ["ca","bb","ac"]
Output: 1
Explanation:
After deleting the first column, A = ["a", "b", "c"].
Now A is in lexicographic order (ie. A[0] <= A[1] <= A[2]).
We require at least 1 deletion since initially A was not in lexicographic order, so the answer is 1.
Example 2:
Input: ["xc","yb","za"]
Output: 0
Explanation:
A is already in lexicographic order, so we don't need to delete anything.
Note that the rows of A are not necessarily in lexicographic order:
ie. it is NOT necessarily true that (A[0][0] <= A[0][1] <= ...)
Example 3:
Input: ["zyx","wvu","tsr"]
Output: 3
Explanation:
We have to delete every column.
Note:
1 <= A.length <= 100
1 <= A[i].length <= 100
這道題說是給了一個字符串數組,里面的字符串長度均相同,這樣如果將每個字符串看作一個字符數組的話,於是就可以看作的一個二維數組,題目要求數組中的字符串是按照字母順序的,問最少需要刪掉多少列。可以看到跟之前那道題 Delete Columns to Make Sorted 的不同之處,那道題是要求每列上的字符都是非遞減順序的,而這道題要求的是字符串是按字母順序的。我們知道比較兩個長度相等的字符串的字母順序時,就是從開頭起按照兩兩對應的位置比較,只要前面的字符順序已經比出來了,后面的字符的順序就不用管了,比如 "bx" 和 "ea",因為 b 比 e 小,所以 "bx" 比 "ea" 小,后面的 x 和 a 的順序無關緊要。如果看成二維數組的話,在比較 A[i][j] 和 A[i+1][j] 時,假如 [0, j-1] 中的某個位置k,已經滿足了 A[i][k] < A[i+1][k]
的話,這里就不用再比了,所以用一個數組 sorted 來標記某相鄰的兩個字符串之間是否已經按照字母順序排列了。然后用兩個 for 循環,外層是遍歷列,內層是遍歷行,然后看若 sorted[i] 為 false,且 A[i][j] > A[i + 1][j]
的話,說明當前列需要被刪除,結果 res 自增1,且 break 掉內層 for 循環。當內層 for 循環 break 掉或者自己結束后,此時看 i 是否小於 m-1,是的話說明是 break 掉的,直接 continue 外層循環。若是自己退出的,則在遍歷一遍所有行,更新一下 sorted 數組即可,參見代碼如下:
class Solution {
public:
int minDeletionSize(vector<string>& A) {
int res = 0, m = A.size(), n = A[0].size(), i = 0, j = 0;
vector<int> sorted(m - 1);
for (j = 0; j < n; ++j) {
for (i = 0; i < m - 1; ++i) {
if (!sorted[i] && A[i][j] > A[i + 1][j]) {
++res;
break;
}
}
if (i < m - 1) continue;
for (i = 0; i < m - 1; ++i) {
sorted[i] |= A[i][j] < A[i + 1][j];
}
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/955
類似題目:
參考資料:
https://leetcode.com/problems/delete-columns-to-make-sorted-ii/