码迷,mamicode.com
首页 > 其他好文 > 详细

【每日一题】- Leetcode 402. Remove K Digits

时间:2020-05-15 00:34:42      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:present   leetcode   which   length   href   mic   rac   etc   this   

Description: 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.


 

Intuition:

1. leftmost distinct digits that determine the superior of the two numbers, e.g. for A=1axxx, B=1bxxx, if the digits a > b, then A > B. So when removing the digits, iterate from the left to right.

2. How to eliminate digits?

Every time comparing the current digit and its left digit, if the left one is larger, eliminate this larger left one. 

3. Implementation: stack data structure

4. Solution:

 

class Solution {
    public String removeKdigits(String num, int k) {
        Stack<Character> s = new Stack<>();
        for (int i = 0; i < num.length(); i++) {
            while (!s.isEmpty() && s.peek() > num.charAt(i) && k > 0) {
                s.pop();
                k--;
            }
            s.push(num.charAt(i));
        }
        
        //remove the remaining digits from the tail
        while (k > 0) {
            s.pop();
            k--;
        }
        
        //build the final string, while removing the leading zeros
        boolean leadingZero = true;
        String ans = "";
        for (char digit : s) {
            if (leadingZero && digit == ‘0‘) continue;
            leadingZero = false;
            ans += digit;
        }
        
        
        if (ans.length() == 0) return "0";
        return ans;
    }
}

 

  

Reference: https://leetcode.com/problems/remove-k-digits/solution/

 

【每日一题】- Leetcode 402. Remove K Digits

标签:present   leetcode   which   length   href   mic   rac   etc   this   

原文地址:https://www.cnblogs.com/yy0506/p/12887597.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!