1. 程式人生 > >【LeetCode】944. Delete Columns to Make Sorted 解題報告(Python)

【LeetCode】944. Delete Columns to Make Sorted 解題報告(Python)

目錄

題目描述

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 a string "abcdef" and deletion indices {0, 2, 3}, then the final string after deletion is “bef”.

Suppose we chose a set of deletion indices D such that after deletions, each remaining column in A is in non-decreasing sorted order.

Formally, the c-th column is [A[0][c], A[1][c], ..., A[A.length-1][c]]

Return the minimum possible value of D.length.

Example 1:

Input: ["cba","daf","ghi"]
Output: 1

Example 2:

Input: ["a","b"]
Output: 0

Example 3:

Input: ["zyx","wvu","tsr"]
Output: 3

Note:

  1. 1 <= A.length <= 100
  2. 1 <= A[i].length <= 1000

題目大意

有一個數組A,其中它的每個元素都是等長度的字串。現在求最短的要刪除的切片的長度,使得做完操作之後,陣列中剩下的相同列是遞增的。

解題方法

又是乍一看很難的題目,其實很簡單的,直接暴力解決就好了。

主要是思路:如果一個列的元素已經是遞增的,那麼我們一定不能把這個列刪除掉。如果刪除掉某一列,那麼其他的列將不受到任何影響。

所以,基於上面兩個原則,我們可以直接對所有的列進行遍歷,也就是說取得所有的列,然後判斷這個列是不是遞增的,如果不是遞增的話,就刪除掉。統計要刪除掉多少個列即可。而判斷某個列是不是遞增的最簡單方法就是排序之後,然後看是不是和之前的相等。

時間複雜度是O(N*(MlogM)),空間複雜度是O(M)。N是每個字串長度,M是陣列長度。還好給的區間很小,直接能過的。

class Solution:
    def minDeletionSize(self, A):
        """
        :type A: List[str]
        :rtype: int
        """
        res = 0
        N = len(A[0])
        for i in range(N):
            col = [a[i] for a in A]
            if col != sorted(col):
                res += 1
        return res

日期

2018 年 11 月 18 日 —— 出去玩了一天,腿都要廢了