2259. 移除指定数字得到的最大结果
2259. 移除指定数字得到的最大结果
题目
You are given a string number
representing a positive integer and a character digit
.
Return _the resulting string after removing exactly one occurrence of _digit
fromnumber
such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit
occurs at least once in number
.
Example 1:
Input: number = "123", digit = "3"
Output: "12"
Explanation: There is only one '3' in "123". After removing '3', the result is "12".
Example 2:
Input: number = "1231", digit = "1"
Output: "231"
Explanation: We can remove the first '1' to get "231" or remove the second '1' to get "123".
Since 231 > 123, we return "231".
Example 3:
Input: number = "551", digit = "5"
Output: "51"
Explanation: We can remove either the first or second '5' from "551".
Both result in the string "51".
Constraints:
2 <= number.length <= 100
number
consists of digits from'1'
to'9'
.digit
is a digit from'1'
to'9'
.digit
occurs at least once innumber
.
题目大意
给你一个表示某个正整数的字符串 number
和一个字符 digit
。
从 number
中 恰好 移除 一个 等于 digit
的字符后,找出并返回按 十进制 表示 最大 的结果字符串。生成的测试用例满足 digit
在 number
中出现至少一次。
解题思路
- 用一个变量
max
来记录最大返回值; - 遍历字符串,找出移除一个
digit
字符后的最大返回值; - 需要注意
number
可能是特别大的整数,因此max
要用BigInt
来表示,且BigInt
实例不能用于Math
对象中的方法,也不能和任何Number
实例混合运算;
代码
/**
* @param {string} number
* @param {character} digit
* @return {string}
*/
var removeDigit = function (number, digit) {
let max = 0,
n = number.length;
for (let i = 0; i < n; i++) {
if (number[i] == digit) {
const num = number.substring(0, i) + number.substring(i + 1);
if (max < BigInt(num)) {
max = BigInt(num);
}
}
}
return max + '';
};
相关题目
题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
---|---|---|---|---|---|
402 | 移掉 K 位数字 | 栈 贪心 字符串 1+ | 🟠 | 🀄️ 🔗 | |
1119 | 删去字符串中的元音 🔒 | 字符串 | 🟢 | 🀄️ 🔗 | |
1796 | 字符串中第二大的数字 | 哈希表 字符串 | 🟢 | 🀄️ 🔗 | |
2844 | 生成特殊数字的最少操作 | 贪心 数学 字符串 1+ | 🟠 | 🀄️ 🔗 |