requirements

You are given an array STRS of n lowercase strings, each of which is of equal length.

These strings can be arranged in a grid, one line at a time. For example, STRS = [” ABC “, “bCE “, “cae”] can be arranged as:

ABC BCE CAE You need to find and delete columns that are not in lexicographical ascending order. In the example above (subscripts start at 0), column 0 (‘a’, ‘b’, ‘c’) and column 2 (‘ C ‘, ‘e’, ‘e’) are all sorted in ascending order, while column 1 (‘b’, ‘C ‘, ‘a’) is not, so column 1 is deleted.

Returns the number of columns you need to delete.

Example 1:

Input: STRS = [" CBA "," DAf "," GHi "] Output: 1 Explanation: The grid looks like this: CBA DAF GHI columns 0 and 2 are in ascending order, but column 1 is not, so only column 1 needs to be deleted.Copy the code

Example 2:

Input: STRS = [" A ","b"] Output: 0Copy the code

Example 3:

Input: STRS = ["zyx"," wVU "," TSR "] Output: 3Copy the code

The core code

class Solution:
    def minDeletionSize(self, strs: List[str]) - >int:
        m,n = len(strs),len(strs[0])
        res = 0
        for i in range(0,n):
            temp = []
            flag = 1
            for j in range(0,m):
                if not temp:
                    temp.append(strs[j][i])
                if strs[j][i] < temp[-1]:
                    flag = 0
                    break
                else:
                    temp.append(strs[j][i])
            if not flag:
                res += 1
        return res
Copy the code

Another way of thinking

class Solution:
    def minDeletionSize(self, strs: List[str]) - >int:
        res = 0
        for i in zip(*strs):
            if sorted(i) ! =list(i):
                res += 1
        return res
Copy the code

If the data in each column is not in ascending order, add 1 to the result, which is time-consuming and not the best way to solve the problem. Second idea: we can use zip(* STRS) to group strings, so that the data in the same column together, easy to compare, and very high efficiency.