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); } } }}