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 innumber
.
Solution 1: Brute Force
Try all possible resulting strings.
Time complexity: O(n2)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 |
// Author: Huahua class Solution { public: string removeDigit(string number, char digit) { const int n = number.size(); string ans(number.size() - 1, '1'); for (int i = 0; i < n; ++i) if (number[i] == digit) ans = max(ans, number.substr(0, i) + number.substr(i + 1)); return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment