[刷题防痴呆] 0402 - 移掉k位数字 (Remove K

2022-01-17  本文已影响0人  西出玉门东望长安

题目地址

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

题目描述

402. Remove K Digits

Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.

 

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.

思路

关键点

代码

class Solution {
    public String removeKdigits(String num, int k) {
        char[] sc = num.toCharArray();
        Deque<Character> stack = new ArrayDeque<>();
        int n = sc.length;

        for (int i = 0; i < n; i++) {
            char c = sc[i];
            while (!stack.isEmpty() && stack.peek() > c && k > 0) {
                stack.pop();
                k--;
            }
            stack.push(c);
        }
        for (int i = 0; i < k; i++) {
            stack.pop();
        }
        StringBuilder sb = new StringBuilder();
        boolean isCheckZero = true;
        while (!stack.isEmpty()) {
            char c = stack.pollLast();
            if (isCheckZero && c == '0') {
                continue;
            }
            isCheckZero = false;
            sb.append(c);
        }
        if (sb.length() == 0) {
            return "0";
        }
        return sb.toString();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读