-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path402.java
More file actions
26 lines (24 loc) · 713 Bytes
/
402.java
File metadata and controls
26 lines (24 loc) · 713 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
class Solution {
public String removeKdigits(String num, int k) {
Stack<Character> st=new Stack<>();
for(int i=0;i<num.length();i++){
int x = num.charAt(i);
while(!st.isEmpty() && st.peek()>x && k>0){
st.pop();
k--;
}
st.push(num.charAt(i));
}
while (k > 0 && !st.isEmpty()) {
st.pop();
k--;
}
StringBuilder sb = new StringBuilder();
while (!st.isEmpty()) sb.append(st.pop());
sb.reverse();
int i = 0;
while (i < sb.length() && sb.charAt(i) == '0') i++;
String ans = sb.substring(i);
return ans.length() == 0 ? "0" : ans;
}
}