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.
Note:
- The length of num is less than 10002 and will be ≥ k.
- The given num does not contain any leading zero.
Example 1:
Input: num = "1432219", k = 3 Output: "1219" Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
Example 2:
Input: num = "10200", k = 1 Output: "200" Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
Example 3:
Input: num = "10", k = 2 Output: "0" Explanation: Remove all the digits from the number and it is left with nothing which is 0.
class Solution { public String removeKdigits(String num, int k) { int le = num.length(); if(k >= le || le == 0) return "0"; while(true){ le = num.length(); if(le == 0) return "0"; if(k-- == 0) return num; if(num.charAt(1) == '0'){ int zeroind = 1; while(zeroind < le && num.charAt(zeroind) == '0'){ zeroind++; } num = num.substring(zeroind); } else{ int i = 0; while(i < le-1){ if(num.charAt(i) > num.charAt(i+1)) {num = num.substring(0, i) + num.substring(i+1); break; } else i++; } if(i == le-1) num = num.substring(0, i); } } } }
参考 https://www.cnblogs.com/271934Liao/p/7083544.html
有几个注意点
1. 每次删除后num位数会减小,需要重新计算num长度
2. 分两种情况
A。第二位是0,那就删掉第一位和第二位以及后面连续的0直到没0,注意这只算删了一位。如果删完了就直接返回0
B。第二位不是0,向后检查直到发现第一个i>i+1为止,为此要设置i<length-1,注意一次只删一位,删完立刻break。如果删到最后一位还是递增,直接删除最后一位