var removeKdigits = function(num, k) { const stk = []; for (const digit of num) { while (stk.length > 0 && stk[stk.length - 1] > digit && k) { stk.pop(); k -= 1; } stk.push(digit); }
for (; k > 0; --k) { stk.pop(); }
let ans = ""; let isLeadingZero = true; for (const digit of stk) { if (isLeadingZero && digit === '0') { continue; } isLeadingZero = false; ans += digit; } return ans === "" ? "0" : ans; };
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Solution: def removeKdigits(self, num: str, k: int) -> str: numStack = [] # 构建单调递增的数字串 for digit in num: while k and numStack and numStack[-1] > digit: numStack.pop() k -= 1 numStack.append(digit) # 如果 K > 0,删除末尾的 K 个字符 finalStack = numStack[:-k] if k else numStack # 抹去前导零 return "".join(finalStack).lstrip('0') or "0"
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcremoveKdigits(num string, k int)string { stack := []byte{} for i := range num { digit := num[i] for k > 0 && len(stack) > 0 && digit < stack[len(stack)-1] { stack = stack[:len(stack)-1] k-- } stack = append(stack, digit) } stack = stack[:len(stack)-k] ans := strings.TrimLeft(string(stack), "0") if ans == "" { ans = "0" } return ans }