-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveKDigits_13May.java
More file actions
50 lines (46 loc) · 1.11 KB
/
RemoveKDigits_13May.java
File metadata and controls
50 lines (46 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
Facts for this solution -
1) 2ms to execute
2) beats 98.33% in terms of time complexity
*/
class Solution {
public String removeKdigits(String num, int k) {
if(num.length() ==k) {
return "0";
}
StringBuffer sb = new StringBuffer(num);
for(int i=0;i<sb.length()-1;) {
if(sb.charAt(i) > sb.charAt(i+1)) {
sb.deleteCharAt(i);
k--;
i--;
if(i<0) {
i=0;
}
} else {
i++;
}
if(k==0) {
break;
}
}
int newLen = sb.length();
while(k>0) {
sb.deleteCharAt(--newLen);
k--;
}
trim(sb);
return sb.toString();
}
public void trim(StringBuffer sb) {
if(sb.length()==1) {
return;
}
if(sb.charAt(0) != '0') {
return;
} else {
sb.deleteCharAt(0);
trim(sb);
}
}
}