-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathRemoveKDigits.java
93 lines (71 loc) · 1.69 KB
/
RemoveKDigits.java
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// @saorav21994
// Stack implementation
// TC : O(n)
// SC : O(n)
class Solution {
public String removeKdigits(String num, int k) {
Stack<Character> st = new Stack<>();
for (char ch : num.toCharArray()) {
while (!st.isEmpty() && st.peek() > ch && k > 0) {
st.pop();
k -= 1;
}
st.push(ch);
}
while (k > 0 && !st.isEmpty()) {
st.pop();
k -= 1;
}
StringBuilder sb = new StringBuilder();
while (!st.isEmpty()) {
sb.append(st.pop());
}
sb = sb.reverse();
// remove leading zeros
int i = 0;
for (char ch : sb.toString().toCharArray()) {
if (ch != '0')
break;
i += 1;
}
String res = sb.toString().substring(i, sb.length());
if (res == "" || res == null)
return "0";
return res;
}
class Solution {
// TC : O(n)
// SC : O(n)
public String removeKdigits(String num, int k) {
Stack<Character> st = new Stack<>();
int i=0;
for(;i<num.length() && k>0;){
while(k>0 && !st.isEmpty() && num.charAt(i)< st.peek()){
st.pop();
k--;
}
st.push(num.charAt(i));
i++;
}
while(!st.isEmpty() && k>0){
st.pop();
k--;
}
String ans = "";
while(!st.isEmpty()){
ans = st.pop() + ans;
}
ans = ans + num.substring(i, num.length());
// 0002000
i = 0;
while(i<ans.length()){
if(ans.charAt(i) == '0'){
i++;
} else {
break;
}
}
// "000000"
return ans.substring(i).length() == 0 ? "0" : ans.substring(i);
}
}