刪除字符串中k個數字使獲得的數字最小 Remove K Digits

問題:git

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:less

  • The length of num is less than 10002 and will be ≥ k.
  • The given num does not contain any leading zero.

Example 1:ui

Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.

Example 2:orm

Input: num = "10200", k = 1
Output: "200"
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.

Example 3:three

Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.

解決:rem

① 字符串

有一個N爲長的數字,用字符串來代替了,如今要求你將它刪除K位,使得其獲得的結果最小。對於每次刪除的狀況有兩種string

(1)假如第一個數不爲0,第二個數爲0,那麼咱們刪除第一個數,就至關於數量級減小2,這樣比刪除獲得的數其餘任何一個方法都小it

(2)另外一種狀況,咱們找到第一次遍歷的局部最大值,即遍歷num第一個知足num.charAt(i)>num.charAt(i+1)的值,刪除這個點,獲得的值最小。這裏就是貪心算法,每次刪除一個局部最大。

class Solution {//6ms     public String removeKdigits(String num, int k) {         StringBuilder sb = new StringBuilder();         int len = num.length();         char[] stack = new char[len];         int count = 0;         for (int i = 0;i < len;i ++){             while(count != 0 && k > 0 && num.charAt(i) < stack[count - 1]){//根據貪心算法刪除比後一個大的值                 count --;                 k --;             }             stack[count ++] = num.charAt(i);         }         int start = 0;         while(start < count && stack[start] == '0') start ++;         return start >= count - k ? "0" : new String(stack,start,count - start - k);     } }

相關文章
相關標籤/搜索