Leetcode 402. Remove K Digits 刪除K個數字 解題報告__leetcode

來源:互聯網
上載者:User
1 解題思想

題目是這樣的,有一個N為長的數字,用字串來代替了,現在要求你將它刪除K位,使得其得到的結果最小

分析:
首先這是一個貪心問題,即我們可以將問題轉化為,一個長度為N的數字裡面,刪除哪個數可以使得數變得最小:
那麼如何刪除呢。
1、因為數字開頭不允許是0,當第二位是0的情況下下,這時候我們刪除了第一位元,那麼至少可以使數字小兩個量級,而其他位置最多也就是小一個數量級,所以這種情況毫無疑問刪除第一個,後面打頭的0也自動消解
2、否則,我們從頭開始找,找到第一個下降的數,如 1234553,那麼最後一個3前面的5就是,刪除它得到的數字是最小的。 2 原題

Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. Note:The length of num is less than 105 and will be ≥ k.The given num does not contain any leading zero.Example 1: Input: num = "1432219", k = 3Output: "1219"Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.Example 2: Input: num = "10200", k = 1Output: "200"Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.Example 3: Input: num = "10", k = 2Output: "0"Explanation: Remove all the digits from the number and it is left with nothing which is 0.
3 AC解
public class Solution {    /**     * 這是一個非常簡單的問題,貪心解決法     * 即 removeKdigits(num,k) = removeKdigits(removeKdigits(num,1),k-1)     * 進行最多K輪的刪除,每次從頭開始尋找一位刪除:     * 1、要麼第二位是0,這樣相當於至少刪了兩位,很值得,必須這麼做     * 2、不然,找到第一個出現下降轉折的位置 刪除     * */    public String removeKdigits(String num, int k) {        int n;        while(true){            n = num.length();            if(n <= k || n == 0) return "0";            if(k-- == 0) return num;            if(num.charAt(1) == '0'){                int firstNotZero = 1;                while(firstNotZero < num.length()  && num.charAt(firstNotZero) == '0') firstNotZero ++;                num=num.substring(firstNotZero);            } else{                int startIndex = 0;                while(startIndex < num.length() - 1  && num.charAt(startIndex) <= num.charAt(startIndex + 1)) startIndex ++;                num=num.substring(0,startIndex)+num.substring(startIndex+1);            }        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.