LeetCode 955. Delete Columns to Make Sorted II

Delete Columns to Make Sorted II Medium

You are given an array of n strings strs, all of the same length.

We may choose any deletion indices, and we delete all the characters in those indices for each string.

完整介绍 https://leetcode.com/problems/delete-columns-to-make-sorted-ii/

这题有点难的是要看懂题目,要删到让所有的词都依词典顺序的排列
做法如下

由左往右,每一列再由上往下,把自己和下一行的字母拿来比,会有三种可能性

自己比下一列的字母大,直接出局,这行要砍掉,answer +1自己比下一列的字母小,通过 (且后面的字母也不用再比了,见下面说明)自己跟下一列的字母相同,注记下来 Repeat

当 Repeat 都没有的时候,程式结束,回传 answer (砍掉几行)

範例题目
http://img2.58codes.com/2024/20105641IZKsRsGq24.jpg

有重覆的字母以 R (Repeat)代表

执行完第一列,会 mark 出两个地方有重覆的字母
http://img2.58codes.com/2024/2010564143BCJkpncv.jpg

后续执行没必要再检查的字母以 「-」表示
执行完第二列,index 2 的 R 会被移除,目标把 R 移光就搞定收工了
http://img2.58codes.com/2024/20105641UcI3asPMIf.jpg

执行第三列会发现这列必须删除,所以 answer + 1
http://img2.58codes.com/2024/20105641f5DgZC5BXa.jpg

执行完第四列后,将 R 全数移光,程式即结束,得到 answer 是 1
http://img2.58codes.com/2024/20105641qAACAnBJbg.jpg

程式码

public class A0955_DeleteColumnsToMakeSortedII {    public int minDeletionSize(String[] strs) {    int ans = 0;    int[] sameNote = new int[strs.length]; // x 轴的长度 (上到下)    // x 轴往右走    for (int x=0; x<strs[0].length(); x++) {        int[] tmpSameNote = sameNote.clone();    boolean isAllLess = true;    boolean isDelete = false;    // y 轴往下走,最后一行不用,所以 -1    for (int y=0; y<strs.length-1; y++) {    if (sameNote[y] == -1)    continue;        char c1 = strs[y].charAt(x);    char c2 = strs[y+1].charAt(x);    if (c1 > c2) {    ans++;    isDelete = true;    break;    }    else if (c1 == c2) {    isAllLess = false;    }    else {    tmpSameNote[y] = -1;        }    }    if (! isDelete) {    sameNote = tmpSameNote;    if (isAllLess)        break;    }    }    return ans;    }}

unit test code

public class A0955_DeleteColumnsToMakeSortedIITest {@Testpublic void testMinDelete() {A0955_DeleteColumnsToMakeSortedII obj = new A0955_DeleteColumnsToMakeSortedII();assertEquals(1, obj.minDeletionSize(new String[] {"ca","bb","ac"}));assertEquals(0, obj.minDeletionSize(new String[] {"xc","yb","za"}));assertEquals(1, obj.minDeletionSize(new String[] {"xga","xfb","yfa"}));assertEquals(3, obj.minDeletionSize(new String[] {"zyx","wvu","tsr"}));assertEquals(1, obj.minDeletionSize(new String[] {"azzzhs","bayygo","ccxxfn", "cdooem", "eznndl", "fzmmck", "fzaxbj", "gzzaai"}));}}

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章