Categories:

Tags:



Problem

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 follows:
abc
bce
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.

Constraints

  • n == strs.length
  • 1 <= n <= 100
  • 1 <= strs[i].length <= 1000
  • strs[i] consists of lowercase English letters.

Solution

The problem Delete Columns to Make Sorted can be solved by scanning the given strings vertically.

Implementation

static const int fast_io = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution
{
  public:
    int minDeletionSize(vector<string> &strs)
    {
        int ret = 0;
        for (int i = 0; i < strs[0].length(); i++)
            for (int j = 0; j < strs.size() - 1; j++)
                if (strs[j][i] > strs[j + 1][i])
                {
                    ret += 1;
                    break;
                }

        return ret;
    }
};