leetcode [402]Remove K Digits

本文探讨了一种算法,旨在从给定的非负整数字符串中删除k个数字,以获得可能的最小数值。通过使用栈结构,文章详细解释了如何在删除过程中保持数字的最小化,同时避免前导零的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

  

转载于:https://www.cnblogs.com/xiaobaituyun/p/11027513.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值