Created
August 6, 2020 16:32
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public String removeKdigits(String num, int k) { | |
Stack<Character> stack = new Stack<Character>(); | |
int i = 0; | |
while (i < num.length()) { | |
// evict bigger digits in the beginning | |
while (k > 0 && !stack.isEmpty() && stack.peek() > num.charAt(i)) { | |
stack.pop(); | |
k--; | |
} | |
stack.push(num.charAt(i++)); | |
} | |
// corner cases like 1234 or 1111 | |
while (k > 0) { | |
stack.pop(); | |
k--; | |
} | |
StringBuilder sb = new StringBuilder(); | |
while (!stack.isEmpty()) { | |
sb.append(stack.pop()); | |
} | |
//reverse stack order | |
sb.reverse(); | |
StringBuilder ans = new StringBuilder(); | |
i = 0; | |
// evict leading 0's | |
while (i < sb.length() && sb.charAt(i) == '0') { | |
i++; | |
} | |
while (i < sb.length()) { | |
ans.append(sb.charAt(i++)); | |
} | |
// return 0 for empty string | |
return ans.length() > 0 ? ans.toString() : "0"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment