402. Remove K Digits

本文介绍两种从数字字符串中移除K个数字的方法:一种是使用队列选择最小数字,另一种是利用栈实现高效删除。两种方法都详细展示了如何保持剩余数字的顺序并构建最终的数字。

我才用的是往队列加需要的字母

public class Solution {
    public String removeKdigits(String num, int k) {

        Queue<Character> queue = new LinkedList<>();
        int len = num.length();
        int nowLen = len - k;//这是个区间长度,比如num="102",k=1开始区间长度为2,因为1,和0可以选,但当加入一位到队列中后,区间长度就变为1(每次减一),因为只有以为可以选,
        int count = 0;//加入字母的数量
        int start = 0;//每次选数开始的地方

        while (count < len - k&&start<len) {
            int index = start;
            int min = num.charAt(start);
            //再选的区间里选最小的数,还要把位置纪录下来
            for (int i = start+1; i <=len- nowLen; i++) {
                if (num.charAt(i) < min) {
                    index = i;
                    min = num.charAt(i);
                }
            }

            queue.offer(num.charAt(index));//选中后加入队列
            count ++;
            start=index+1;//下次的开始位置
            nowLen--;
        }
        StringBuffer stringBuffer =  new StringBuffer();
        if (queue.isEmpty())return  "0";

        int flag=0;
     //来处理像“”0003210"这样开头是0的数
        while (!queue.isEmpty()){
            if (flag==0&&queue.peek()=='0'){
                queue.poll();
            }else if (flag==0&&queue.peek()!='0'){
                stringBuffer.append(queue.poll());
                flag=1;
            }else{
                stringBuffer.append(queue.poll());
            }

        }

       if(stringBuffer.toString().equals(""))return "0";
        return stringBuffer.toString();
    }

}

我还看到了一个往栈里加字母(通过删除法)的方法,好像是标答,方法挺好的

public class Solution {
    public String removeKdigits(String num, int k) {
        int len = num.length();
        //corner case
        if(k==len)        
            return "0";

        Stack<Character> stack = new Stack<>();
        int i =0;
        while(i<num.length()){
            //whenever meet a digit which is less than the previous digit, discard the previous one
            //只要不超过删除k的数量,只要有当前的数比栈中的数小,就把栈的数删了,放它进入。删了的数就算被永久的删了,不再考虑了
            while(k>0 && !stack.isEmpty() && stack.peek()>num.charAt(i)){
                stack.pop();
                k--;
            }
            stack.push(num.charAt(i));
            i++;
        }

        // corner case like "1111"
        while(k>0){
            stack.pop();
            k--;            
        }

        //construct the number from the stack
        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty())
            sb.append(stack.pop());
        sb.reverse();

        //remove all the 0 at the head
        while(sb.length()>1 && sb.charAt(0)=='0')
            sb.deleteCharAt(0);
        return sb.toString();
    }
}
LeetCode402题“Remove K Digits”中,你需要从一个非负整数的数组(表示为字符串形式)中移除k个数字,使得剩下的数字按顺序组成最小的非负整数。这里是一个简单的C语言解决方案: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> // Function to find the minimum number after removing k digits char* removeKdigits(char* num, int k) { int n = strlen(num); if (k >= n) return ""; // Initialize a stack for storing indices int minStack[5] = {n}, top = 0; for (int i = 0; i < n; ++i) { while (top > 0 && num[i] < num[minStack[top - 1]]) { // Remove digit at index minStack[top - 1] num[minStack[top - 1]] = '\0'; --minStack[top--]; } // Push current index onto the stack if not full and still need to remove more digits if (k > 0 && num[i] != '0') { minStack[++top] = i; --k; } } // If all k digits removed or reached the beginning of the number if (k == 0) { num[minStack[0]] = '\0'; // Convert it back to an integer return num; } else { // Fill in the remaining positions with zeros memmove(num + 1, num + minStack[0] + 1, n - minStack[0]); num[0] = '0'; // Add a zero at the beginning return num; } } int main() { char* num = "1432219"; int k = 3; char* result = removeKdigits(num, k); printf("Minimum number after removing %d digits: %s\n", k, result); free(result); // Don't forget to free the dynamically allocated memory return 0; } ``` 在这个程序中,我们维护了一个栈,用于保存需要删除的小数字的索引。遍历输入字符串,每次遇到比栈顶元素小的数字,就将其后面的数字依次向前移动并删除。同时检查是否还有剩余的k值,如果有的话,继续将当前数字入栈。最后,根据剩余的k值处理结果。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值