Skip to content

3798. Largest Even Number

Description

You are given a string s consisting only of the characters '1' and '2'.

You may delete any number of characters from s without changing the order of the remaining characters.

Return the largest possible resultant string that represents an even integer. If there is no such string, return the empty string "".

Β 

Example 1:

Input: s = "1112"

Output: "1112"

Explanation:

The string already represents the largest possible even number, so no deletions are needed.

Example 2:

Input: s = "221"

Output: "22"

Explanation:

Deleting '1' results in the largest possible even number which is equal to 22.

Example 3:

Input: s = "1"

Output: ""

Explanation:

There is no way to get an even number.

Β 

Constraints:

  • 1 <= s.length <= 100
  • s consists only of the characters '1' and '2'.

Solutions

Solution 1

1
2
3
class Solution:
    def largestEven(self, s: str) -> str:
        return s.rstrip("1")
1
2
3
4
5
6
7
8
9
class Solution {
    public String largestEven(String s) {
        int i = s.length();
        while (i > 0 && s.charAt(i - 1) == '1') {
            i--;
        }
        return s.substring(0, i);
    }
}
1
2
3
4
5
6
7
8
9
class Solution {
public:
    string largestEven(string s) {
        while (!s.empty() && s.back() == '1') {
            s.pop_back();
        }
        return s;
    }
};
1
2
3
func largestEven(s string) string {
    return strings.TrimRight(s, "1")
}
1
2
3
function largestEven(s: string): string {
    return s.replace(/1+$/, '');
}

Comments