chengchengxu15 / CS-leaning

1 stars 1 forks source link

402. Remove K Digits #21

Closed chengchengxu15 closed 3 years ago

chengchengxu15 commented 3 years ago

https://leetcode.com/problems/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.

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.

solution:

https://leetcode-cn.com/problems/remove-duplicate-letters/solution/yi-zhao-chi-bian-li-kou-si-dao-ti-ma-ma-zai-ye-b-4/

chengchengxu15 commented 3 years ago

重点: 理解while 那一行

class Solution:
    def removeKdigits(self, num: str, k: int) -> str:
        stack = []
        remain = len(num) - k
        if remain <= 0:
            return str(0)
        for digit in num:
            ### k 看是否还需要删除,stack:看stack是否空,
            while k and stack and stack[-1] > digit:
                stack.pop()
                k -= 1
            stack.append(digit)
        return str(int(''.join(stack[:remain])))