From 6f1c291e146e6fd8ca06e30081ca98d3a1ced1a4 Mon Sep 17 00:00:00 2001 From: ductnn Date: Thu, 11 Apr 2024 23:34:06 +0700 Subject: [PATCH] add sol --- leetcode/402.RemoveKDigits/sol.go | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 leetcode/402.RemoveKDigits/sol.go diff --git a/leetcode/402.RemoveKDigits/sol.go b/leetcode/402.RemoveKDigits/sol.go new file mode 100644 index 0000000..637f1d1 --- /dev/null +++ b/leetcode/402.RemoveKDigits/sol.go @@ -0,0 +1,33 @@ +// https://leetcode.com/problems/remove-k-digits + +package main + +import ( + "fmt" +) + +func removeKdigits(num string, k int) string { + stk, remain := make([]byte, 0), len(num)-k + for i := 0; i < len(num); i++ { + n := len(stk) + for k > 0 && n > 0 && stk[n-1] > num[i] { + stk = stk[:n-1] + n, k = n-1, k-1 + } + stk = append(stk, num[i]) + } + + for i := 0; i < len(stk) && i < remain; i++ { + if stk[i] != '0' { + return string(stk[i:remain]) + } + } + return "0" +} + +func main() { + num := "1432219" + k := 3 + + fmt.Println(removeKdigits(num, k)) +}