forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0402-remove-k-digits.java
More file actions
38 lines (27 loc) · 824 Bytes
/
0402-remove-k-digits.java
File metadata and controls
38 lines (27 loc) · 824 Bytes
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
class Solution {
public String removeKdigits(String num, int k) {
if(k==num.length() || k>num.length()){
return "0";
}
Stack<Character> st=new Stack<>();
for(int i=0;i<num.length();i++){
char ch=num.charAt(i);
while(!st.isEmpty() && k>0 && st.peek()>ch){
st.pop();
k--;
}
st.push(ch);
}
while(!st.isEmpty() && k>0){
st.pop();
k--;
}
StringBuilder sb = new StringBuilder();
while(!st.isEmpty())
sb.append(st.pop());
sb.reverse();
while(sb.length()>1 && sb.charAt(0)=='0')
sb.deleteCharAt(0);
return sb.toString();
}
}