website/content.en/ChapterFour/0400~0499/0402.Remove-K-Digits.md
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.
Note:
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.
Given a non-negative integer num represented as a string, remove k digits from this number so that the remaining number is the smallest possible.
Note:
Scan each digit of num from the beginning and push them onto a stack in order. When the new digit is smaller than the top element of the stack, keep moving backward and remove all digits that are larger than this new digit. Note that the final requirement is to make the remaining number as small as possible. If the remaining number has more than K digits at the end, taking the first K digits must be the smallest (because if the last K digits contained values smaller than the first K digits, the larger digits in front would have been removed).
Note that although num does not contain leading 0s, after deleting digits in the middle, for example after deleting all digits before a 0, leading 0s may appear. They should be removed when producing the final output.
package leetcode
func removeKdigits(num string, k int) string {
if k == len(num) {
return "0"
}
res := []byte{}
for i := 0; i < len(num); i++ {
c := num[i]
for k > 0 && len(res) > 0 && c < res[len(res)-1] {
res = res[:len(res)-1]
k--
}
res = append(res, c)
}
res = res[:len(res)-k]
// trim leading zeros
for len(res) > 1 && res[0] == '0' {
res = res[1:]
}
return string(res)
}