Given string A representative a positive integer which has N digits, remove any k digits of the number, the remaining digits are arranged according to the original order to become a new positive integer.
Find the smallest integer after remove k digits.
N <= 240 and k <= N,
Example
Given an integer A = "178542", k = 4
return a string "12"
The idea is to replace the larger number with the smaller number after it.
For example, A = "178542", k = 4
So the final result is 12
Time: O(n)
Space: O(n)
public class Solution {
/**
*@param A: A positive integer which has N digits, A is a string.
*@param k: Remove k digits.
*@return: A string
*/
public String DeleteDigits(String A, int k) {
Stack<Integer> stack = new Stack<>();
for (char c : A.toCharArray()) {
int num = c - '0';
while (k > 0 && !stack.isEmpty() && num < stack.peek()) {
stack.pop();
k--;
}
stack.push(num);
}
while (k > 0) {
stack.pop();
k--;
}
// construct result
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
String result = sb.reverse().toString();
// skip leading 0
int start = 0;
while (result.charAt(start) == '0') {
start++;
}
// handle special case
if (start == result.length()) {
return "0";
}
return result.substring(start);
}
}