|
| 1 | +import java.util.Stack; |
| 2 | + |
| 3 | +/** |
| 4 | + * Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. |
| 5 | + * <p> |
| 6 | + * Note: |
| 7 | + * The length of num is less than 10002 and will be ≥ k. |
| 8 | + * The given num does not contain any leading zero. |
| 9 | + * <p> |
| 10 | + * Example 1: |
| 11 | + * Input: num = "1432219", k = 3 |
| 12 | + * Output: "1219" |
| 13 | + * Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. |
| 14 | + * <p> |
| 15 | + * Example 2: |
| 16 | + * Input: num = "10200", k = 1 |
| 17 | + * Output: "200" |
| 18 | + * Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. |
| 19 | + * <p> |
| 20 | + * Example 3: |
| 21 | + * Input: num = "10", k = 2 |
| 22 | + * Output: "0" |
| 23 | + * Explanation: Remove all the digits from the number and it is left with nothing which is 0. |
| 24 | + * <p> |
| 25 | + * Created by drfish on 6/13/2017. |
| 26 | + */ |
| 27 | +public class _402RemoveKDigits { |
| 28 | + public String removeKdigits(String num, int k) { |
| 29 | + if (num.length() <= k) { |
| 30 | + return "0"; |
| 31 | + } |
| 32 | + Stack<Character> stack = new Stack<>(); |
| 33 | + int index = 0; |
| 34 | + // remove digit which is bigger than its next one |
| 35 | + while (index < num.length()) { |
| 36 | + while (k > 0 && !stack.isEmpty() && stack.peek() > num.charAt(index)) { |
| 37 | + stack.pop(); |
| 38 | + k--; |
| 39 | + } |
| 40 | + stack.push(num.charAt(index)); |
| 41 | + index++; |
| 42 | + } |
| 43 | + while (k > 0) { |
| 44 | + stack.pop(); |
| 45 | + k--; |
| 46 | + } |
| 47 | + // construct new number |
| 48 | + StringBuilder sb = new StringBuilder(); |
| 49 | + while (!stack.isEmpty()) { |
| 50 | + sb.append(stack.pop()); |
| 51 | + } |
| 52 | + sb.reverse(); |
| 53 | + // remove zeros at the head |
| 54 | + while (sb.length() > 0 && sb.charAt(0) == '0') { |
| 55 | + sb.deleteCharAt(0); |
| 56 | + } |
| 57 | + return sb.toString(); |
| 58 | + } |
| 59 | + |
| 60 | + public static void main(String[] args) { |
| 61 | + _402RemoveKDigits solution = new _402RemoveKDigits(); |
| 62 | + assert "1219".equals(solution.removeKdigits("1432219", 3)); |
| 63 | + assert "200".equals(solution.removeKdigits("10200", 1)); |
| 64 | + assert "0".equals(solution.removeKdigits("10", 2)); |
| 65 | + } |
| 66 | +} |
0 commit comments