1 ideas for solving problems
The title is this, there is a number of n for long, replaced by a string, now requires you to remove it K-bit, so that it gets the smallest result
Analysis:
First of all, this is a greedy question, that is, we can turn the problem into a number with a length of N, and delete which number makes the number smaller:
So how to delete it.
1, because the beginning of the number is not allowed to be 0, when the second digit is 0, then we delete the first digit, then at least we can make the number small two orders of magnitude, and the other position is a small order of magnitude, so this situation no doubt delete the first, followed by the beginning of the 0 also automatically dissolve
2, otherwise, we start from scratch, find the first drop of the number, such as 1234553, then the last 3 front 5 is, delete it to get the smallest number. 2 Original question
Given a non-negative integer num represented as a string, remove K digits from the "number so" the new number is the SM Allest possible.
Note: The
length of num is less than and would 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 FO RM the new number 1219 which is the smallest.
Example 2:
input:num = "10200", K = 1
Output: "Explanation:remove" the leading 1 and the number is
200. Note This output must not contain leading zeroes.
Example 3:
input:num = "Ten", K = 2
Output: "0" explanation:remove all of the digits from the number and
it I s left with no which is 0.
3 AC Solution
public class Solution {/** * This is a very simple question, the greedy solution * namely removekdigits (num,k) = Removekdigits (removekdigits ) * k-1) * To remove the maximum K-round, each time from scratch to find a delete: * 1, or the second is 0, so that the equivalent of at least delete two, it is worthwhile, must do so * 2, otherwise, find the first occurrence of a decline in the position delete * * * *
Ublic string removekdigits (string num, int k) {int n;
while (true) {n = num.length ();
if (n <= k | | n = 0) return "0";
if (k--= = 0) return num;
if (Num.charat (1) = = ' 0 ') {int firstnotzero = 1;
while (Firstnotzero < Num.length () && num.charat (firstnotzero) = = ' 0 ') Firstnotzero + +;
Num=num.substring (Firstnotzero);
} else{int startIndex = 0;
while (StartIndex < Num.length ()-1 && num.charat (startIndex) <= Num.charat (StartIndex + 1)) StartIndex + +;
Num=num.substring (0,startindex) +num.substring (startindex+1); }
}
}
}