Skip to content

Latest commit

 

History

History
25 lines (23 loc) · 560 Bytes

402.md

File metadata and controls

25 lines (23 loc) · 560 Bytes

406. Remove K Digits

Solution 1 (time O(n)), space O(n))

class Solution(object):
    def removeKdigits(self, num, k):
        """
        :type num: str
        :type k: int
        :rtype: str
        """
        stack = []
        for digit in num:
            while stack and k and stack[-1] > digit:
                stack.pop()
                k -= 1
            stack.append(digit)
        if k > 0:
            stack = stack[:-k]
        ans = "".join(stack).lstrip('0')
        if not ans:
            return "0"
        return ans