402. Remove K Digits
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。如果删到最后一位还是递增,直接删除最后一位
class Solution { public String removeKdigits(String num, int k) { int n = num.length(); if(n == k) return "0"; Stack<Character> stack = new Stack(); int i = 0; while(i < n) { while(k > 0 && !stack.isEmpty() && stack.peek() > num.charAt(i)) { k--; stack.pop(); } stack.push(num.charAt(i)); i++; } while(k != 0) { k--; stack.pop(); } StringBuilder sb = new StringBuilder(); while(!stack.isEmpty()) sb.append(stack.pop()); while(sb.length() > 1 && sb.charAt(sb.length() - 1) == '0') sb.deleteCharAt(sb.length() - 1); return sb.reverse().toString(); } }
神说,要用stack,本质上是stack + greedy的方法
greedy,把所有char存到stack中,如果stack peek 大于当前的char,就要把这个stack peek给pop掉。如果stack push完所有的char了k还没用完,说明有相等的数或者升序1234出现,那么继续pop完所有的。
然后把所有的0开头的去掉剩下的就是答案。

浙公网安备 33010602011771号