LeetCode 944. Delete Columns to Make Sorted
考点 | 难度 |
---|---|
Array | Easy |
题目
You are given an array of n
strings strs
, all of the same length.
The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"]
can be arranged as:
You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 (‘a’, ‘b’, ‘c’) and 2 (‘c’, ‘e’, ‘e’) are sorted while column 1 (‘b’, ‘c’, ‘a’) is not, so you would delete column 1.
思路
每一列都检查有没有后一位index大于前一位的情况,如果有,count
加一。
答案
public int minDeletionSize(String[] A) {
int count = 0;
for (int i = 0; i < A[0].length(); i++) {
for (int j = 1; j < A.length; j++) {
if (A[j-1].charAt(i) > A[j].charAt(i)) {
count++;
break;
}
}
}
return count;
}