LeetCode 402. Remove K Digits

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.git

Note:
The length of num is less than 10002 and will be ≥ k.
The given num does not contain any leading zero.github

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:app

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:less

Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.

描述

給定一個以字符串表示的非負整數 num,移除這個數中的 k 位數字,使得剩下的數字最小。ui

注意:code

num 的長度小於 10002 且 ≥ k。
num 不會包含任何前導零。orm

示例 1 :three

輸入: num = "1432219", k = 3
輸出: "1219"
解釋: 移除掉三個數字 4, 3, 和 2 造成一個新的最小的數字 1219。

示例 2 :ip

輸入: num = "10200", k = 1
輸出: "200"
解釋: 移掉首位的 1 剩下的數字爲 200. 注意輸出不能有任何前導零。

示例 3 :

輸入: num = "10", k = 2
輸出: "0"
解釋: 從原數字移除全部的數字,剩餘爲空就是0。

來源:力扣(LeetCode)
連接:https://leetcode-cn.com/probl...
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。

思路

  • 使用棧,須要指明的是,在字符形式下,依然有 "1" < "2" ... < "9".
  • 咱們依次把數字(字符格式)壓入棧中;每次壓入的時候都和棧頂的數作比較,若是棧頂的數比較大,就把棧頂的數 pop 出來(循環檢查),直到要壓入棧的數小於等於棧頂的數;統計從棧中 pop 出數的個數 cnt,若是cnt 超過了給定的 k;則再也不比較,直接壓入棧中;
  • 若是當前要壓入的數爲 "0",而且棧爲空,那麼跳過次數,不壓入棧中;
# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-09-07 07:59:40
# @Last Modified by:   何睿
# @Last Modified time: 2019-09-07 09:10:06


class Solution:
    def removeKdigits(self, num: str, k: int) -> str:

        cnt, stack = 0, []
        for n in num:
            while cnt < k and stack and n < stack[-1]:
                cnt += 1
                stack.pop()
            if n == "0" and not stack:
                continue
            stack.append(n)

        return "".join(stack[0:len(stack) - (k - cnt)]) or "0"

源代碼文件在 這裏
©本文首發於 何睿的博客 ,歡迎轉載,轉載需保留 文章來源 ,做者信息和本聲明.

相關文章
相關標籤/搜索