99网
您的当前位置:首页955. Delete Columns to Make Sorted II

955. Delete Columns to Make Sorted II

来源:99网

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 <= A.length <= 100
1 <= A[i].length <= 100

class Solution {
public:
    void op(int no,vector<string>& A,vector<string>& res,int& same_tag,int& reverse_tag)
    {//no表示每个字符串中的第no个字符下标 
        for(int i=0;i<A.size()-1;i++)
        {
        	if(res[i]+A[i][no]>res[i+1]+A[i+1][no]) {reverse_tag=1;return;}
        	if(res[i]+A[i][no]==res[i+1]+A[i+1][no]) same_tag=1;
		}
    }
    int minDeletionSize(vector<string>& A) {
//把字符串数组看作二元数组,每个串的第一个字符组成第一列,第二个字符组成第二列,以此类推 
//same_tag表示某一列中有相同元素,需继续检查下一列,reverse_tag表示某一列不符合要求,删掉该列,继续对下一列进行检查
        int ans=0,same_tag=0,reverse_tag=0;
        vector<string>res(A.size());//用来存储已检查过的列
        for(int i=0;i<A[0].size();i++)
        {
            same_tag=0,reverse_tag=0;
            op(i,A,res,same_tag,reverse_tag);
            if(reverse_tag) ans++;//存在后一个字符比前一个字符小的情况,删除该列字符,ans++
            else
            {
                if(!same_tag) return ans;//reverse_tag,same_tag都为0,直接返回ans
                for(int j=0;j<A.size();j++)
                    res[j]+=A[j][i];
            }
        }
        return ans;
    }
};

因篇幅问题不能全部显示,请点此查看更多更全内容