File tree 1 file changed +31
-0
lines changed
May-LeetCoding-Challenge/13-Remove-K-Digits 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ object Solution {
2
+ def removeKdigits (num : String , k : Int ): String =
3
+ if (num.length == k) " 0"
4
+ else trimLeftZero(removeKdigitsWithAcc(num, num.length - k, " " ))
5
+
6
+ def removeKdigitsWithAcc (num : String , restNumberLength : Int , acc : String ): String = {
7
+ if (restNumberLength == 0 ) acc
8
+ else if (num.length == restNumberLength) acc + num
9
+ else {
10
+ val rightIndexEnd = num.length - restNumberLength
11
+ var smallestNumberIndex = 0
12
+ var smallestNumber = num.head
13
+ var index = 1
14
+ while (index <= rightIndexEnd && smallestNumber != '0' ) {
15
+ if (num(index).toInt < smallestNumber.toInt) {
16
+ smallestNumber = num(index)
17
+ smallestNumberIndex = index
18
+ }
19
+ index += 1
20
+ }
21
+ val newAcc = acc + smallestNumber
22
+ removeKdigitsWithAcc(num.drop(smallestNumberIndex + 1 ), restNumberLength - 1 , newAcc)
23
+ }
24
+ }
25
+
26
+ def trimLeftZero (num : String ): String = {
27
+ val leftZeroDroppedNumber = num.dropWhile(_ == '0' )
28
+ if (leftZeroDroppedNumber.isEmpty) " 0" else leftZeroDroppedNumber
29
+ }
30
+
31
+ }
You can’t perform that action at this time.
0 commit comments