删列造序

给你由 n 个小写字母字符串组成的数组 strs,其中每个字符串长度相等。这些字符串可以每个一行,排成一个网格。例如,strs = ["abc", "bce", "cae"] 可以排列为:

  1. abc
  2. bce
  3. cae

你需要找出并删除 不是按字典序升序排列的 列。在上面的例子(下标从 0 开始)中,列 0('a', 'b', 'c')和列 2('c', 'e', 'e')都是按升序排列的,而列 1('b', 'c', 'a')不是,所以要删除列 1 。返回你需要删除的列数。

Delete Columns to Make Sorted

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:

  1. abc
  2. bce
  3. cae

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. Return the number of columns that you will delete.

  1. Input: strs = ["cba","daf","ghi"]
  2. Output: 1
  3. Explanation: The grid looks as follows:
  4. cba
  5. daf
  6. ghi
  7. Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.
  1. Input: strs = ["a","b"]
  2. Output: 0
  3. Explanation: The grid looks as follows:
  4. a
  5. b
  6. Column 0 is the only column and is sorted, so you will not delete any columns.
  1. Input: strs = ["zyx","wvu","tsr"]
  2. Output: 3
  3. Explanation: The grid looks as follows:
  4. zyx
  5. wvu
  6. tsr
  7. All 3 columns are not sorted, so you will delete all 3.
  • n == strs.length
  • 1 <= n <= 100
  • 1 <= strs[i].length <= 1000
  • strs[i] 由小写英文字母组成 / strs[i] consists of lowercase English letters.

这个题的话是给我们一个矩阵,然后让我们判断一下不是单调递增的然后输出列数,所以这个题目直接模拟一遍就可以了,然后是代码怎么写:

  1. class Solution {
  2. public:
  3. int minDeletionSize(vector<string>& strs) {
  4. // n的话代表列数,m的话代表行数
  5. int n=strs.size(),m=strs[0].size();
  6. // 定义一下答案
  7. int res=0;
  8. // 然后我们枚举一下所有列
  9. for(int i=0;i<m;i++) {
  10. // 然后判断一下它是不是递增的
  11. bool flag=true;
  12. // 从这一层第一行开始
  13. for(int j=1;j<n;j++) {
  14. // 如果我们发现第j行第i列是小于第j-1行第i列
  15. if(strs[j][i]<strs[j-1][i])
  16. // 说明它不是单调递增的
  17. flag=false;
  18. // 然后我们判断一下如果flag是true的话,说明这一行是单调递增的
  19. // 反之则不是单调递增的
  20. // 这题是问我们有多少列不是单调递增的
  21. }
  22. if(!flag) res++;
  23. }
  24. return res;
  25. }
  26. };
  1. func minDeletionSize(strs []string) int {
  2. res:=0
  3. n,m:=len(strs),len(strs[0])
  4. for i:=0;i<m;i++ {
  5. for j:=1;j<n;j++ {
  6. if strs[j][i]<strs[j-1][i] {
  7. res++
  8. break
  9. }
  10. }
  11. }
  12. return res
  13. }