Skip to content

2259. Remove Digit From Number to Maximize Result 👍

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
9
class Solution {
 public:
  string removeDigit(string number, char digit) {
    for (int i = 0; i + 1 < number.length(); ++i)
      if (number[i] == digit && digit < number[i + 1])
        return number.erase(i, 1);
    return number.erase(number.rfind(digit), 1);
  }
};
1
2
3
4
5
6
7
8
class Solution {
  public String removeDigit(String number, char digit) {
    for (int i = 0; i + 1 < number.length(); ++i)
      if (number.charAt(i) == digit && digit < number.charAt(i + 1))
        return new StringBuilder(number).deleteCharAt(i).toString();
    return new StringBuilder(number).deleteCharAt(number.lastIndexOf(digit)).toString();
  }
}
1