LeetCode -- remove k it 移除k位

229 阅读1分钟

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.

大意:给定非负整数作为字符串,从其中移除k位,让这个数是最小值。最后的值不包括前缀0值(也就是前缀是0要删除)

解法:使用贪心算法,借助栈结构,从左到右遍历入栈,每次入栈都使得栈底-》栈顶是递增数列(在k>0的情况下)

    1. 基本操作:在k>0 && 栈不为空的情况下,如果要入栈的值小于栈顶值,移除栈顶,k--,
    1. 继续步骤1,否则入栈该值
    1. 如果k>0,移除栈中的k个值
    1. 出栈到字符串然后反转首位,移除前缀0,即为最终结果。

代码如下:

class Solution {
    public String removeKdigits(String num, int k) {
        if(k == 0){
            return num;
        }
        if(k == num.length()){
            return "0";
        }
        
        Stack<Character> stack = new Stack();
        for(char ch: num.toCharArray()){
            while(k>0 && !stack.isEmpty() && stack.peek() > ch){
                stack.pop();
                k--;
            }
            stack.push(ch);
        }
        while(k-->0){
            stack.pop();
        }
        
        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty()){
            sb.append(stack.pop());
        }
        sb.reverse();
        while(sb.length()>1 &&sb.charAt(0)=='0'){
            sb.deleteCharAt(0);
        }
        return sb.toString();
    }
}