LeetCode周赛#114 Q3 Delete Columns to Make Sorted II

题目来源:https://leetcode.com/contest/weekly-contest-114/problems/array-of-doubled-pairs/

问题描述

 955. Delete Columns to Make Sorted II

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 an array A = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef","vyz"].

Suppose we chose a set of deletion indices D such that after deletions, the final array has its elements in lexicographic order (A[0] <= A[1] <= A[2] ... <= A[A.length - 1]).

Return the minimum possible value of D.length.

 

Example 1:

Input: ["ca","bb","ac"]
Output: 1
Explanation: 
After deleting the first column, A = ["a", "b", "c"].
Now A is in lexicographic order (ie. A[0] <= A[1] <= A[2]).
We require at least 1 deletion since initially A was not in lexicographic order, so the answer is 1.

Example 2:

Input: ["xc","yb","za"]
Output: 0
Explanation: 
A is already in lexicographic order, so we don't need to delete anything.
Note that the rows of A are not necessarily in lexicographic order:
ie. it is NOT necessarily true that (A[0][0] <= A[0][1] <= ...)

Example 3:

Input: ["zyx","wvu","tsr"]
Output: 3
Explanation: 
We have to delete every column.

 

Note:

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

------------------------------------------------------------

题意

给定一个字符串矩阵,问最少删掉矩阵的多少列,可以使得字符串矩阵按字典序排列

------------------------------------------------------------

思路

删除列计数器初始为0;

维护一个字符串矩阵B,表示当前访问列之前删去最少列后形成的字典序字符串矩阵。

对字符串矩阵逐列分析:

1. 该列严格单调增,直接返回;

2. 该列不严格单调增,更新B,进入下一列;

3. 该列不增,删除列计数器+1;

------------------------------------------------------------

代码

class Solution {
public:
    int minDeletionSize(vector<string>& A) {
        int cnt = 0, p = 0, q = 0, P = A[0].size(), Q = A.size(), flag = 0;
        // flag = 0,1,2: strictly increase, not strictly increase, not increase
        vector<string> B(Q);
        for (p=0; p<P; p++)
        {
            flag = 0;
            for (q=0; q<Q-1; q++)
            {
                if (B[q] + A[q].substr(p, 1) > B[q+1] + A[q+1].substr(p, 1))
                {
                    flag = 2;
                    break;
                }
                else if (B[q] + A[q].substr(p, 1) == B[q+1] + A[q+1].substr(p, 1))
                {
                    flag = 1;
                }
            }
            if (flag == 2)
            {
                cnt++;
            }
            else if (flag == 0)
            {
                break;
            }
            if (flag != 2)
            {
                for (q=0; q<Q; q++)
                {
                    B[q].append(A[q], p, 1);
                }
            }
        }
        return cnt;
    }
};

猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/85085035