LeetCode 402. Remove K Digits 除去K个数,使得结果最小

Question:

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.

思路:

贪心算法,同时用栈比较适合处理。从前向后压入栈中,贪心规则是进制位越前的数字,越要取小的,遇到后面的更小,就把前面的删了。如19546要删除两个,肯定从前向后看,删前面最大的。当9进入栈中,后面5来了,因为5<9,并且需要删两个数,就把9放弃,又遇到4,把5也放弃,以此获取最小值。

看Example知道有几个triky的地方。

存在0怎么办,最后全删了怎么办,遍历了数组之后K还不为0怎么办?这些是特殊情况,需要注意。

原题链接:https://leetcode.com/problems/remove-k-digits/description/

class Solution {
    public String removeKdigits(String num, int k) {
        //use stack to solve this problem
        
        Stack<Character> num_stack = new Stack<Character> ();
        int len = num.length();
        //1.
        //“10” 2 出错,所以加上了这个判断
        if(k==len)
            return "0";
    
        for(int i = 0;i<len;i++)
        {   
            //k>0,还能删除数字
            //若栈顶元素大于当前值,则把较大的栈顶元素去除,不选择。
            //!num_stack.empty() 若结果栈为空,直接压栈
            //num_stack.empty()!=0是错误的,返回的是boolean
            //2.
            //用while不是if
            while(k>0 && !num_stack.empty() && num_stack.peek()>num.charAt(i) )
            {         
              num_stack.pop();
              k--;
           }
          //3.
          //很重要,若栈空且数字为0,则第一位为0,就不放进去,否则就会少了一位,或几位
         //  if(!(num_stack.empty() && num.charAt(i)=='0') ) 这是错误的,对“10” 1不通过
            num_stack.push(num.charAt(i));
            
        }
        //4.
        //若遍历完数字,K仍大于0,则是如12345的数字,后面的字符比前面的大,上面的条件删不掉,从后向前pop()
        while(k > 0)
        {
            num_stack.pop();
            k--;
        }
        
       
        //构造结果!不太会
        StringBuilder result = new StringBuilder();
        
        while(!num_stack.isEmpty())
        {  
            result.append(num_stack.pop());
        }
        result.reverse();
        
        //5.
        //remove all the 0 at the head
        while(result.length()>1 && result.charAt(0)=='0')
            result.deleteCharAt(0);
       
        //StringBuilder result = new StringBuilder();
        return result.toString();
    }
}
这样运行时间在总体的50%左右,但是有很快的也贴出来参考:


public class Solution {
    public String removeKdigits(String num, int k) {
        int digits = num.length() - k;
        char[] stk = new char[num.length()];
        int top = 0;
        // k keeps track of how many characters we can remove
        // if the previous character in stk is larger than the current one
        // then removing it will get a smaller number
        // but we can only do so when k is larger than 0
        for (int i = 0; i < num.length(); ++i) {
            char c = num.charAt(i);
            while (top > 0 && stk[top-1] > c && k > 0) {
                top -= 1;
                k -= 1;
            }
            stk[top++] = c;
        }
        // find the index of first non-zero digit
        int idx = 0;
        while (idx < digits && stk[idx] == '0') idx++;
        return idx == digits? "0": new String(stk, idx, digits - idx);
    }
}
博主学习记录,转载请注明出处,谢谢~
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值