跳至主要內容

2259. 移除指定数字得到的最大结果


2259. 移除指定数字得到的最大结果open in new window

🟢   🔖  贪心 字符串 枚举  🔗 力扣open in new window LeetCodeopen in new window

题目

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 in number.

题目大意

给你一个表示某个正整数的字符串 number 和一个字符 digit

number 中 恰好 移除 一个 等于 digit 的字符后,找出并返回按 十进制 表示 最大 的结果字符串。生成的测试用例满足 digitnumber 中出现至少一次。

解题思路

  • 用一个变量 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 位数字open in new window 贪心 字符串 1+
1119删去字符串中的元音 🔒open in new window字符串
1796字符串中第二大的数字open in new window哈希表 字符串
2844生成特殊数字的最少操作open in new window贪心 数学 字符串 1+