We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents bcd4d7b + 215b016 commit 6b03699Copy full SHA for 6b03699
kotlin/0402-remove-k-digits.kt
@@ -0,0 +1,18 @@
1
+class Solution {
2
+ fun removeKdigits(num: String, k: Int): String {
3
+ val stack = Stack<Char>() //monotonic stack
4
+ var count = k
5
+ for(i in 0 until num.length){
6
+ while(count > 0 && !stack.isEmpty() && num[i] < stack.peek()){
7
+ stack.pop() //remove the larger int
8
+ count--
9
+ }
10
+ stack.push(num[i])
11
12
+ repeat(count){ //pop the last k integers (largest integers)
13
+ stack.pop()
14
15
+ val sum = stack.joinToString("")
16
+ return if(sum == "") "0" else sum.toBigInteger().toString() //to int to remove all leading Zeros, instead of using Strinbuilder
17
18
+}
0 commit comments