Leetcode 2259. Remove Digit From Number to Maximize Result
You are given a string number
representing a positive integer and a character digit
. You need to remove one occurrence of digit
from number
so that the resulting string is the largest possible integer. Return the resulting string as an integer in string format.
Example:
Input: number = "1231", digit = '1'
Output: "231"
Input: number = "551", digit = '5'
Output: "51"
Input: number = "123", digit = '3'
Output: "12"
digit
in the number
?
number
contain leading zeros after removing the digit?
number
is a valid positive integer, so there won’t be leading zeros.digit
.number
:
number
.digit
, consider the number formed by removing the current occurrence of digit
.digit
and determine the maximum of these numbers.public class Solution {
public String removeDigit(String number, char digit) {
String maxNumber = "";
int length = number.length();
for (int i = 0; i < length; i++) {
if (number.charAt(i) == digit) {
String candidate = number.substring(0, i) + number.substring(i + 1);
if (maxNumber.isEmpty() || candidate.compareTo(maxNumber) > 0) {
maxNumber = candidate;
}
}
}
return maxNumber;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.removeDigit("1231", '1')); // Output: "231"
System.out.println(sol.removeDigit("551", '5')); // Output: "51"
System.out.println(sol.removeDigit("123", '3')); // Output: "12"
}
}
number
of length n
once, performing substring operations which are O(n) in total. Thus, the overall time complexity is O(n).digit
. Hence, the space complexity is also O(n).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?