Given a string ' str ' of digits and an integer ' n ', build the lowest possible number by removing ' n ' digits from the string And not changing the order of input digits.
Examples:
Input:str = "4325043", n = 3 Output: "2043"
Input:str = "765028321", n = 5 Output: "0221"
Input:str = "121198", n = 2 Output: "1118"
Solution One: The goal is to get a string representation of the smallest number, so to make high-level numbers as small as possible, you can use greedy strategy, from left to right to scan the numbers in the string, compare adjacent two numbers, if the left side of the number is larger than the right, you should delete the left number, otherwise, two pointers to the right one Until the last two digits are compared or the number of deleted numbers equals N, and if the number of deleted numbers is n ', assuming n ' is less than N, then a special case is that assuming N ' is 0, indicating that the numbers in the string are in ascending order, at this point, You only need to delete the last n digits of a string. The code for Java is as follows:
public class Lowestnumber {
public string Lowestnumber (string str, int n) {
if (n <= 0) {
return str;
}
int len = Str.length ();
if (n >= len) {
Return "";
}
String rst = "";
int l = 0;
int r = 1;
int d = 0;
while ((d < n) && (R < len)) {
char cl = Str.charat (L);
char cr = Str.charat (R);
if (CL <= cr) {
RST + = string.valueof (CL);
} else {
D + = 1;
}
L = r;
R + = 1;
}
if (d = = 0) {
Return str.substring (0, len-n);
}
RST + = str.substring (l);
Return Lowestnumber (RST, n-d);
}
}
The least time complexity of solution one should be O (nm), where m represents the length of the input string. Obviously a one-off deletion is too inefficient, in fact, we will notice the fact that, assuming that the input string length is M, the number of characters that need to be removed is n, then the minimum value in the first n+1 character must be in the result string, which can be proved by the method, assuming that the former n+ 1 characters Embox is not in the result string, the length of the output string is less than m-n, so does not meet the requirements, and assuming that the non-minimum value of the first n+1 string in the result string, it is obvious that a smaller result string, so based on this, we can find the first n+1 characters in the minimum value, Then remove all numbers from the first to the minimum, and then start with the first character after the minimum value, recursively. This is the solution two, you can refer to: http://www.geeksforgeeks.org/build-lowest-number-by-removing-n-digits-from-a-given-number/in the code;
Build Lowest number by removing n digits from a given number