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.

Note:

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

 

Example 1:

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:

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:

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

题目大意:

给定一个非负的整数字符串,从这个字符串中删除k个数字,得到最大的一个字符串。

解法:

利用一个stack存储字符,一旦栈顶元素大于遍历的元素,便将栈顶元素去除。然后将所有栈顶元素进行拼接。如果说删除的元素还没有k个,这时从栈底到栈顶都是递增的,直接删除栈顶元素即可。还要对元素进行处理,防止有前导0元素的出现。

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

  

posted @ 2019-06-15 14:32  小白兔云  阅读(134)  评论(0编辑  收藏  举报