Skip to content

Commit

Permalink
Time: 69 ms (14.18%), Space: 48.3 MB (20.16%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
saikatkar committed Apr 1, 2022
1 parent bbe25a1 commit b4458cd
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions 402-remove-k-digits/402-remove-k-digits.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution {
public String removeKdigits(String num, int k) {
Stack<Character> stack = new Stack<>();
char[] numArr = num.toCharArray();
for (int i = 0; i < numArr.length; i++) {
while (!stack.isEmpty() && stack.peek() > numArr[i] && k > 0) {
stack.pop();
k--;
}
stack.push(numArr[i]);
}

while (k > 0 && !stack.isEmpty()) {
stack.pop();
k--;
}
Stack<Character> tempStack = new Stack<>();
while (!stack.isEmpty()) {
tempStack.push(stack.pop());
}
while(!tempStack.isEmpty() && tempStack.peek() == '0') {
tempStack.pop();
}
char [] result = new char[tempStack.size()];
int i = 0;
while (!tempStack.isEmpty()) {
result[i++] = tempStack.pop();
}
return result.length == 0 ? "0" : String.valueOf(result);
}
}

0 comments on commit b4458cd

Please sign in to comment.