RemoveKDigits { public String removeKdigits(String num, int k) { if (k >= num.length()) { return "0"; } char[] cn = num.toCharArray(); StringBuilder sb = new StringBuilder(); Stack<Character> stack = new Stack<>(); int i = 0; while (i < cn.length && k > 0) { char c = cn[i]; if (stack.size() == 0) { if (c != '0') { stack.push(c); } i++; } else { if (stack.peek() > c) { char pc = stack.pop(); k--; } else { stack.push(c); i++; } } } while (k > 0) { stack.pop(); k--; } while (!stack.isEmpty()) { sb.insert(0, stack.pop()); } if (sb.length() == 0) { while (i < cn.length && cn[i] == '0') { i++; } } while (i < cn.length) { sb.append(cn[i]); i++; } return sb.length() == 0 ? "0" : sb.toString(); }  String removeKdigits(String num, int k);  }
@Test(dataProvider = "kDigits") public void testRemovekDigits(String kDigits, int k, String removed) { assertEquals(new RemoveKDigits().removeKdigits(kDigits, k), removed); }