leetcode [402]Remove K Digits

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.java

Note:git

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

 

Example 1:app

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

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

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

題目大意:orm

給定一個非負的整數字符串,從這個字符串中刪除k個數字,獲得最大的一個字符串。blog

解法:three

利用一個stack存儲字符,一旦棧頂元素大於遍歷的元素,便將棧頂元素去除。而後將全部棧頂元素進行拼接。若是說刪除的元素尚未k個,這時從棧底到棧頂都是遞增的,直接刪除棧頂元素便可。還要對元素進行處理,防止有前導0元素的出現。rem

java:字符串

class Solution {
    public String removeKdigits(String num, int k) {
        Stack<Character>stack=new Stack<>();
        stack.push(num.charAt(0));
        int i=1;
        while (i<num.length()){
            while (!stack.empty() && stack.peek()>num.charAt(i) && k>0){
                stack.pop();
                k--;
            }
            stack.push(num.charAt(i));
            i++;
        }
        while (k>0){
            stack.pop();
            k--;
        }
        StringBuilder sb=new StringBuilder();
        for (Character c:stack){
            sb.append(c);
        }
        while (sb.length()>0 && sb.charAt(0)=='0'){
            sb.deleteCharAt(0);
        }

        return sb.length()==0?"0":sb.toString();
    }
}
相關文章
相關標籤/搜索