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,
Given an integer A = "178542"
, k = 4
return a string "12"
Analysis:
When take current number n from string A, we need to compare the last digit we have in the new string, if n is greater than the last number in the new string, we do nothing. However, if n is less than the last digit in the new string, should we replace it? we can if we have
newString.length() + A.length() - p > A.length() - k.
1 class Solution { 2 public String removeKdigits(String num, int k) { 3 if (num == null || num.length() == 0 || k <= 0) return num; 4 if (num.length() <= k) return "0"; 6 StringBuilder sb = new StringBuilder(); 8 9 for (int p = 1; p < num.length(); p++) { 10 //这题关键的部分是如果当前这个数比前一个数小,我们就一定要把当前这个数替换掉前一个数。因为这样我们得到的数就一定更小。 11 // 但是也不是可以无限替换,我们得保证num后面部分的substring长度+当前sb的长度 >= num.length() - k 12 while (sb.length() >= 1 && num.charAt(p) < sb.charAt(sb.length() - 1) && sb.length() > p - k) { 13 sb.deleteCharAt(sb.length() - 1); 14 } 15 if (sb.length() < num.length() - k) { 16 sb.append(num.charAt(p)); 17 } 18 } 19 // remove the extra 0 at the beginning 20 while(sb.length() > 1 && sb.charAt(0) == '0') { 21 sb.deleteCharAt(0); 22 } 23 return sb.toString(); 24 } 25 }