LeetCode 402. Remove K Digits

本文介绍了一种算法,用于从一个非负整数中移除k位数字,使得剩余数字尽可能小,同时保持原有数字顺序不变。通过使用StringBuffer进行高效操作,文章详细阐述了解决方案的步骤,并提供了完整的Java实现代码。

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

1.题目

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个数字字符,使其值最小。(不能改变原始字符的相对顺序)

2.解题思路

 采取StringBuffer存储字符串,因为其对字符的操作比较简便。
1)由字符串第一位数字不是0,若其后第二位开始有连续的0值出现,则直接删除第一位数,可达到一下子消灭多位数的效果。(且仅限第一个字符可以这样)
2)若第一位数后不是0,则需要去挨个比较当前字符与前一个字符的大小
若当前字符小于前一个字符,则直接删除前一个字符 ,如1432219中 出现下降转折的就有4 3 2;(遵守不改变原字符顺序的情况下删除当前子段中最大的字符,即贪心原则);
若当前字符不小于前一个字符,则直接往后进行遍历;
3)我们在进行删除的时候要统计当前删除的字符个数count,在循环结束后要拿出来与k值对比
若count=k,则说明数字字符串已经在遍历的时候就删除完成;
若count<k,则说明原字符串或其截取后的子串一定是一个递增不减的序列,如12333344这种,故此时我们只需要在该字符串的最后删除k-count个字符即可;

3.JAVA代码

    public String removeKdigits(String num, int k) {
    	int len = num.length();
    	if(k == len)
    		return "0";
    	if(k == 0)
    		return num;
    	StringBuffer sb = new StringBuffer(num);
    	int count = 0; //记录当前删除字符的个数
    	//循环k次,每次旨在删除一个字符
    	for(int i=0;i<k;i++){
    		//由于字符串放在StringBuffer中,则当 第一位数被删除后,就会有后面的数顶上,所以每次循环时都应该判断第一位数的情况
        	if(sb.charAt(1) == '0'){
        		//按照思路1),将第一位数和其后连续的所有0值全部删除
        		int firstNotZero = 1;
        		while(firstNotZero<sb.length()&&sb.charAt(firstNotZero)=='0')
        			firstNotZero++;
        		sb.delete(0, firstNotZero);
        		count++;
        	}else{
        		//按照思路2),寻找“转折数”然后直接删除
            	for(int j=1;j<sb.length();j++){
            		if(sb.charAt(j)-'0' < sb.charAt(j-1)-'0'){
            			sb.deleteCharAt(j-1);
            			count++;
            			break;
            		}
            	}
        	}
    	}
    	//当上面循环没能达到删除次数时,表明此时的StringBuffer中的字符串已经是递增不减的,删除最后k-count字符即可
    	if(count < k){
    		sb.delete(sb.length()-(k-count), sb.length());
    	}
    	if(sb.length() == 0)
    		return "0";
        return  sb.toString();
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值