LeetCode 2259. Remove Digit From Number to Maximize Result

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

移走一个指定数字让剩下的变成最小,这个数字可能出现好几次,那其实就有两种情况:

1. 这个数字的下一位更大,那显然把它移走的话剩下的就最大了。

2. 这个数字的下一位更小,那就需要再观察观察,但如果都是这样的话,那就移走最后一个,剩下的最大。

于是写成代码就是这样的:

class Solution {
    public String removeDigit(String number, char digit) {
        int lastIndex = 0;
        for (int i = 0; i < number.length(); i++) {
            if (number.charAt(i) == digit) {
                lastIndex = i;
                if (i < number.length() - 1) {
                    if (number.charAt(i) < number.charAt(i + 1)) {
                        return number.substring(0, i) + number.substring(i + 1, number.length());
                    }
                }
            }
        }
        return number.substring(0, lastIndex) + number.substring(lastIndex + 1, number.length());
    }
}

也看到有人用sort + stream做,非常fancy:LeetCode - The World's Leading Online Programming Learning Platform

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值