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.java
Note:git
Example 1:app
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:less
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:ui
Input: num = "10", k = 2 Output: "0" Explanation: Remove all the digits from the number and it is left with nothing which is 0.
题目大意:orm
给定一个非负的整数字符串,从这个字符串中删除k个数字,获得最大的一个字符串。blog
解法:three
利用一个stack存储字符,一旦栈顶元素大于遍历的元素,便将栈顶元素去除。而后将全部栈顶元素进行拼接。若是说删除的元素尚未k个,这时从栈底到栈顶都是递增的,直接删除栈顶元素便可。还要对元素进行处理,防止有前导0元素的出现。rem
java:字符串
class Solution { public String removeKdigits(String num, int k) { Stack<Character>stack=new Stack<>(); stack.push(num.charAt(0)); int i=1; while (i<num.length()){ while (!stack.empty() && stack.peek()>num.charAt(i) && k>0){ stack.pop(); k--; } stack.push(num.charAt(i)); i++; } while (k>0){ stack.pop(); k--; } StringBuilder sb=new StringBuilder(); for (Character c:stack){ sb.append(c); } while (sb.length()>0 && sb.charAt(0)=='0'){ sb.deleteCharAt(0); } return sb.length()==0?"0":sb.toString(); } }